开发者

Getting an image from NSGraphicsContext

开发者 https://www.devze.com 2023-01-18 22:26 出处:网络
How can I get the drawing in开发者_StackOverflow a graphics context as an image?If its graphics port is a CGBitmapContext, you can create an image from that.

How can I get the drawing in开发者_StackOverflow a graphics context as an image?


If its graphics port is a CGBitmapContext, you can create an image from that.

But that's not something you want to rely on. If the context's graphics port isn't a CGBitmapContext, you're screwed. Moreover, there's no safe way to tell whether it's a CGBitmapContext or not.

So, really, you can't create an image from an NSGraphicsContext.

This leads to the question of alternatives.

If it's an NSView that's drawing into the context, problem solved: You can ask the view for a PDF of what it draws, and (if necessary) create an image from that. Or, lock focus on the view and create an NSBitmapImageRep from the focused view. Neither one of these will work inside drawRect: (the latter may work, but I wouldn't trust it to not call drawRect:).

If you think you need this image within drawRect: in order to rubber-stamp some drawing into multiple places, there are two much-better solutions: Move that drawing code into another method and call it every time you need to draw that, or create a CGLayer, draw the image once into it, and then draw the CGLayer as needed. Drawing the same thing repeatedly is what CGLayers exist for.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号