我试着用pyobjc在图像上覆盖一些文本,同时努力回答我的问题,
"Annotate images using tools built into OS X"
. 通过引用
CocoaMagic
,用Rubyobjc替代
RMagick
,我想到了:
#!/usr/bin/env python
from AppKit import *
source_image = "/Library/Desktop Pictures/Nature/Aurora.jpg"
final_image = "/Library/Desktop Pictures/.loginwindow.jpg"
font_name = "Arial"
font_size = 76
message = "My Message Here"
app = NSApplication.sharedApplication() # remove some warnings
# read in an image
image = NSImage.alloc().initWithContentsOfFile_(source_image)
image.lockFocus()
# prepare some text attributes
text_attributes = NSMutableDictionary.alloc().init()
font = NSFont.fontWithName_size_(font_name, font_size)
text_attributes.setObject_forKey_(font, NSFontAttributeName)
text_attributes.setObject_forKey_(NSColor.blackColor, NSForegroundColorAttributeName)
# output our message
message_string = NSString.stringWithString_(message)
size = message_string.sizeWithAttributes_(text_attributes)
point = NSMakePoint(400, 400)
message_string.drawAtPoint_withAttributes_(point, text_attributes)
# write the file
image.unlockFocus()
bits = NSBitmapImageRep.alloc().initWithData_(image.TIFFRepresentation)
data = bits.representationUsingType_properties_(NSJPGFileType, nil)
data.writeToFile_atomically_(final_image, false)
当我运行它时,我得到:
Traceback (most recent call last):
File "/Users/clinton/Work/Problems/TellAtAGlance/ObviouslyTouched.py", line 24, in <module>
message_string.drawAtPoint_withAttributes_(point, text_attributes)
ValueError: NSInvalidArgumentException - Class OC_PythonObject: no such selector: set
在文档中查找drawatpoint:withattributes:,它说,“只有当nsview有焦点时才应该调用这个方法。”nsImage不是nsview的子类,但我希望它可以工作,而且在ruby示例中,类似的东西似乎可以工作。
我需要做什么改变才能使这个工作成功?
我重写了代码,忠实地将它转换为Objy-C基础工具。它工作,没有问题。[如果有理由,我很乐意在这里发布。]
问题就变成了,如何做到:
[message_string drawAtPoint:point withAttributes:text_attributes];
不同于
message_string.drawAtPoint_withAttributes_(point, text_attributes)
?有没有一种方法来判断哪个“oc-pythonobject”引发了nsinvalidargumentexception?