Search code examples
objective-cxcodemacosxcode4nsrect

Update NSRect Color or Redraw


what I am trying to do is have an NSSlider and whenever I change the value I want it to update the color of my NSRect. Will I need to remove my NSRect and redraw it every time I want to change the color or how would I go about this? If I have to remove the Rect and redraw it how would I do that?

Thanks!

Heres the Method

arrowX is just an integer but what I want to change with the slider is the [[NSColor colorWithDeviceWhite:0 alpha:0.4] setFill]; specifically the alpha value between 0 and 1

- (void)drawRect:(NSRect)theRect
{
    NSRect contentRect = NSInsetRect([self bounds], 0, 0);
    NSBezierPath *path = [NSBezierPath bezierPath];

    [path moveToPoint:NSMakePoint(_arrowX, NSMaxY(contentRect))];
    [path lineToPoint:NSMakePoint(_arrowX / 2, NSMaxY(contentRect))];
    [path lineToPoint:NSMakePoint(NSMaxX(contentRect), NSMaxY(contentRect))];

    NSPoint topRightCorner = NSMakePoint(NSMaxX(contentRect), NSMaxY(contentRect));
    [path curveToPoint:NSMakePoint(NSMaxX(contentRect), NSMaxY(contentRect))
         controlPoint1:topRightCorner controlPoint2:topRightCorner];

    [path lineToPoint:NSMakePoint(NSMaxX(contentRect), NSMinY(contentRect))];

    NSPoint bottomRightCorner = NSMakePoint(NSMaxX(contentRect), NSMinY(contentRect));
    [path curveToPoint:NSMakePoint(NSMaxX(contentRect), NSMinY(contentRect))
         controlPoint1:bottomRightCorner controlPoint2:bottomRightCorner];

    [path lineToPoint:NSMakePoint(NSMinX(contentRect), NSMinY(contentRect))];

    [path curveToPoint:NSMakePoint(NSMinX(contentRect), NSMinY(contentRect))
         controlPoint1:contentRect.origin controlPoint2:contentRect.origin];

    [path lineToPoint:NSMakePoint(NSMinX(contentRect), NSMaxY(contentRect))];

    NSPoint topLeftCorner = NSMakePoint(NSMinX(contentRect), NSMaxY(contentRect));
    [path curveToPoint:NSMakePoint(NSMinX(contentRect), NSMaxY(contentRect))
         controlPoint1:topLeftCorner controlPoint2:topLeftCorner];

    [path lineToPoint:NSMakePoint(_arrowX / 2, NSMaxY(contentRect))];
    [path closePath];

    //SETTING THE VALUE OF 1 = WHITE AND 0 = BLACK.
    [[NSColor colorWithDeviceWhite:0 alpha:0.4] setFill];
    [path fill];

    [NSGraphicsContext saveGraphicsState];

    NSBezierPath *clip = [NSBezierPath bezierPathWithRect:[self bounds]];
    [clip appendBezierPath:path];
    [clip addClip];

    [NSGraphicsContext restoreGraphicsState];
}

Solution

  • You need to add an instance variable that stores your NSColor. In your slider's action method, set the instance variable to the new color, and send setNeedsDisplay:YES to the view.