Search code examples
objective-ccocoansviewdrawrectnsimage

Drawing Transparent Images


I created a custom view to a button, as I need to implement some highlighting when the mouse is over. The class is very simple, and I already implemented mouseEntered: as well as mouseExited:. The view was registered for tracking in the init method (not sure if it's the best place).

The problem is drawing. I keep an ivar mouseOver, set to YES on mouse enter and NO on mouse exited. The other ivar is for the image, called image. The difference between mouse over or not when it comes to drawing, is the transparency. Here is my drawRect::

- (void)drawRect:(NSRect)dirtyRect
{
    [image drawAtPoint:NSMakePoint(0.0,0.0)
              fromRect:dirtyRect
             operation:NSCompositeCopy
              fraction:((mouseOver) ? 1.0 : 0.0)];
}

It works nicely, but only when the mouse first entered, apparently. I guess the problem is that the view is not cleared before drawing the other image. I tried adding:

[[NSColor clearColor] set];
NSRectFillUsingOperation(dirtyRect, NSCompositeClear);

But without success. How can I fix this?


Solution

  • [NSColor clearColor] is a purely transparent color. You probably want to fill using a color with some opacity, like, say, [NSColor whiteColor].