[Pythonmac-SIG] Cocoa graphics and context management

Dinu Gherman gherman at darwin.in-berlin.de
Tue Sep 16 06:29:28 EDT 2003


Hi,

I'm exploring possibilities to use Cocoa graphics (NSView/NSImages)
in more detail. Below I've appended a simple test script which does
what I expect, but it causes many warnings (errors?) at runtime like
these:

   kCGErrorFailure : CGContextSetFillColorSpace: invalid context
   kCGErrorFailure : CGContextSetFillColor: invalid context
   kCGErrorFailure : CGContextSetStrokeColorSpace: invalid context
   ...

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?

Ideally, I want a standalone tool without building a whole appli-
cation around it that makes use of window servers and what not...

Thanks,

Dinu




#!/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


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."

         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)
         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__':
     unittest.main()




More information about the Pythonmac-SIG mailing list