I need to use custom drawing to draw an NSImage.

Discussion in 'Mac Programming' started by ausername, May 7, 2009.

  1. ausername macrumors newbie

    Feb 28, 2009
    I want to draw an NSImage into a custom view. But once the image is drawn, I want to draw NSRects over the image... But when I try drawing an NSRect, it replaces the NSImage I had drawn from before. The only way I can fix this is redrawing the image every time, this is slow because the image is very large (2500 X 1250). So, what I need is a way to draw an NSImage, and then draw things on the image, without replacing the image.

    Can this be done in custom drawing?

    Thanks in advance.
  2. Catfish_Man macrumors 68030


    Sep 13, 2001
    Portland, OR
    CoreAnimation might work well for this. Put the image on one layer, then have the rects on layers above it and let the compositing system handle it.
  3. kpua macrumors 6502

    Jul 25, 2006
    NSView composites everything into a single buffer, so once something is drawn over, it's gone completely and needs to be redrawn.

    I agree with Catfish_Man. If you use layer-backed views, or just CALayers, you can avoid redrawing the image, since the layers retain their contents after they have been composited. That means they can be moved, reordered, etc. and then recomposited without having to invalidate the layers' contents.
  4. ausername thread starter macrumors newbie

    Feb 28, 2009
    Hmm, I tried using core animation, but I don't know it very well. I need to know how to add an image to a CALayer, and how to add my own custom NSRect to a layer. If this is a simple task, could I see some example code? Thanks. :)
  5. kpua macrumors 6502

    Jul 25, 2006
    If you can convert your image to a CGImageRef, you can just set the layer's contents with it.

    layer.contents = myCGImage;
    You can also set the background color of the layers with a CGColorRef:

    layer.backgroundColor = myCGColor;
    Then set the layer's rect to the rect you want them to be drawn in, and make them sublayers of the image layer (or perhaps sibling layers located above the image layer).

    For more details, read the documentation for CoreAnimation, and specifically, CALayer.

Share This Page