在我的自定义 NSSlider 中使用 CoreGraphics 在 Cocoa 中绘制错误

Faulty drawings in Cocoa with CoreGraphics at my custom NSSlider

我必须重新设计一些控件。 NSButton 没有问题,但 NSSlider 在我按住鼠标并移动旋钮时出现绘图错误。如果我松开鼠标,它就会正确绘制。

这是绘图代码(我的class继承自NSSlider):

- (void)drawRect:(NSRect)dirtyRect
{
    //[super drawRect:dirtyRect];
    CGContextRef c;
    CGFloat y, r, p;

    c = [[NSGraphicsContext currentContext] graphicsPort];
    r = (dirtyRect.size.height*0.8)/2.0;
    p = (dirtyRect.size.width-r*2) * ([self doubleValue]*0.01);
    y = dirtyRect.size.height/2.0;

    CGContextSetLineWidth(c, 2);
    CGContextSetStrokeColorWithColor(c, [_fullLineColor CGColor]);
    CGContextMoveToPoint(c, 0, y);
    CGContextAddLineToPoint(c, dirtyRect.size.width, y);
    CGContextStrokePath(c);

    CGContextSetLineWidth(c, 5);
    CGContextSetStrokeColorWithColor(c, [_valueLineColor CGColor]);
    CGContextMoveToPoint(c, 0, y);
    CGContextAddLineToPoint(c, p, y);
    CGContextStrokePath(c);

    CGContextSetFillColorWithColor(c, [_knobColor CGColor]);
    CGContextFillEllipseInRect(c, CGRectMake(p, y-r, r*2, r*2));
}

我该怎么做才能避免这种行为?

parameter dirtyRect

A rectangle defining the portion of the view that requires redrawing. This rectangle usually represents the portion of the view that requires updating. When responsive scrolling is enabled, this rectangle can also represent a nonvisible portion of the view that AppKit wants to cache.

您正在 dirtyRect 中绘制控件。您应该在 self.bounds 中绘制控件(的 dirtyRect 部分)。 在 documentation of drawRect:

中阅读更多内容