[Pythonmac-SIG] Cocoa graphics and context management
Etienne Posthumus
etienne at cs.vu.nl
Tue Sep 16 07:15:48 EDT 2003
On dinsdag, sep 16, 2003, at 12:29 Europe/Amsterdam, Dinu Gherman wrote:
> I suspect this is because of some graphics context I don't care at
> all about, isn't it? Does anybody have an idea how to improve this?
Hi Dinu
I am just a starting to get my head around Cocoa so take everything I
say with a bag of salt... :-)
I think the error messages are because there is no connection to the
window server.
You need to set up an NSApp and make a window for the view to be
connected to.
I have added some lines of code, and then it runs the test without
errors.
Try the script as changed below.
gr.
Etienne
#!/usr/bin/env python
"test_nsview.py - saving simple Cocoa graphics in a PDF file."
import os, unittest
from objc import YES, NO
from AppKit import NSView, NSColor, NSBezierPath, NSWindow
import AppKit
class MyView(NSView):
"A simple view containing a blue filled ellipse."
def drawRect_(self, aRect):
col = NSColor.blueColor()
col.set()
path = NSBezierPath.bezierPathWithOvalInRect_(aRect)
path.setLineWidth_(0)
path.stroke()
path.fill()
class TestNSView(unittest.TestCase):
def test0(self):
"Create a simple graphic PDF file."
my_window = NSWindow.alloc()
my_window.initWithContentRect_styleMask_backing_defer_( ((0,
0), (200, 100)) , 0, AppKit.NSBackingStoreBuffered, NO)
path = "test_nsview0.pdf"
if os.path.exists(path):
os.remove(path)
# create a view
frame = ((0,0), (200, 100))
view = MyView.alloc().initWithFrame_(frame)
my_window.setContentView_(view)
view.drawRect_(frame)
# save it
pdfData = view.dataWithPDFInsideRect_(frame)
pdfData.writeToFile_atomically_(path, YES)
self.assert_(os.path.exists(path), "PDF not saved!")
if __name__=='__main__':
NSApp = AppKit.NSApplication.sharedApplication()
unittest.main()
More information about the Pythonmac-SIG
mailing list