Search code examples
macoscocoacore-graphicsquartz-2d

Displaying a CGContextRef


How can I draw a CGContextRef created with CGBitmapContextCreate() to a NSView?

Should I convert it to a image first? If that's the case, wouldn't it be an expensive operation?


Solution

  • Should I convert it to a image first?

    Yes. You can use CGBitmapContextCreateImage, then use that to draw into the graphics context from drawRect:.

    If that's the case, wouldn't it be an expensive operation?

    CGBitmapContext->CGImage one option among multiple - use the best for the task. If you make good design decisions, it's rarely an obstacle.

    CGImage, NSImage, and UIImage are immutable. They avoid copying you might expect when they are created.

    Larger images can obviously consume a good amount of memory, and it can be expensive to draw the image to the bitmap, and then to draw the image at a size other than its native size.

    Reuse the images you create, and hold on to them appropriately. Profile now and then to see how things are going.