Search code examples
cocoadrawingdrawrectclippingnsbezierpath

Matt Gemmell's NSBezierPath+StrokeExtensions draws outside of clip rect


I'm using Matt Gemmell's NSBezierPath+StrokeExtensions category to draw an inside stroke on an NSRect. Here is the code for the entire category:

- (void)strokeInside
{
    /* Stroke within path using no additional clipping rectangle. */
    [self strokeInsideWithinRect:NSZeroRect];
}

- (void)strokeInsideWithinRect:(NSRect)clipRect
{
    NSGraphicsContext *thisContext = [NSGraphicsContext currentContext];
    float lineWidth = [self lineWidth];

    /* Save the current graphics context. */
    [thisContext saveGraphicsState];

    /* Double the stroke width, since -stroke centers strokes on paths. */
    [self setLineWidth:(lineWidth * 2.0)];

    /* Clip drawing to this path; draw nothing outwith the path. */
    [self setClip];

    /* Further clip drawing to clipRect, usually the view's frame. */
    if (clipRect.size.width > 0.0 && clipRect.size.height > 0.0) {
        [NSBezierPath clipRect:clipRect];
    }

    /* Stroke the path. */
    [self stroke];

    /* Restore the previous graphics context. */
    [thisContext restoreGraphicsState];
    [self setLineWidth:lineWidth];
}

Here is my drawRect: method:

- (void)drawRect:(NSRect)dirtyRect {
    NSRect myRect = NSMakeRect(500, 0, 400, 100);
    [[NSColor colorWithCalibratedRed:0 green:0 blue:1.0 alpha:0.5] set];
    NSRectFillUsingOperation(myRect, NSCompositeSourceOver);

    [[NSColor blueColor] set];
    [[NSBezierPath bezierPathWithRect:myRect] strokeInside];
}

However, this happens when I scroll up:

enter image description here

As you can see, the inside stroke draws onto the toolbar. Why does this happen? How can I fix the strokeInside method? Note, this does not happen with the regular stroke method.


Solution

  • OK, I figured it out. Instead of this line:

    [self setClip];

    Use this:

    [self addClip];

    Works fine and makes sense.