問題描述
如何為自定義 NSImageRep 子類實現 ‑draw (How to implement ‑draw for custom NSImageRep subclass)
I'm interested in creating an NSImageRep subclass that can hold double precision values. The standard NSBitmapImageRep can hold single precision floats, but chokes on doubles. I like that the NSBitmapImageRep exposes the data buffer for manipulation, and I'd like to retain the ability to manipulate the data in place rather than manipulate a separate buffer that I'll need to convert into an image for display.
I think subclassing is fairly straight forward except I'm not sure how to handle the most basic part: drawing the image. The documentation lists ‑draw as a method I need to implement, which makes sense, but what is the best way to draw a bitmap?
I saw one hesitant suggestion to draw lots of little rectangles, one per pixel presumably: How to Implement Custom Image representation for NSImage
Is there a more efficient approach? I've looked and can't find a worked example of a custom NSImageRep with bitmap data‑‑ most examples use vector data.
Also, I find it interesting that the method to implement is simply ‑draw, and not any form of bounded draw. Is there a way to determine what the current clipping region is from within the NSImageRep or something to avoid drawing parts of the image that aren't necessary?
參考解法
方法 1:
I’m sure you’ve found a solution for this post by this point, but here’s my findings if you’re still interested.
What I’ve found in implementing my own NSImageRep
is that there are many inefficient ways of doing it, and that you don’t necessarily have to implement only the starkly simple ‑(BOOL)draw
method. If you provide an implementation of ‑(BOOL)drawInRect:
, it will be used instead in most cases. In fact, in my NSImageRep
subclass, I have yet to see ‑(BOOL)draw
being called when ‑(BOOL)drawInRect:
is present.
For the actual drawing, I’ve been using Core Graphics, which allows you to create images from raw data and draw it with a great deal of control and precision, all while being extremely fast. My representation is still rather crude, yet it’s fast even when dealing with large images.
The whole subject direly lacks documentation, likely due to there being little need for additional representations outside of the old standards (TIFF, PNG, JPEG, etc). It’s rather frustrating to do research on so if I get the time I’ll see about writing up a blog post detailing everything I’ve run across.
(by Omegaman、John Wells)