无论我如何尝试,可可中的NSView都拒绝重绘

时间:2019-02-15 15:28:00

标签: xcode macos cocoa nsview

我正在Mac上编写一个应用程序以测量屏幕上的颜色。为此,我有一个ColorView用特定的颜色填充bezierpath。测量时,大多数修补程序都可以很好地进行,但是在给定的时刻,重绘错开并且视图不再更新。我已经寻找了一段时间,尝试了许多建议的解决方案。它们都不是防水的。

我的实际代码:

    [colorView setColor:[colorsForMeasuring objectAtIndex:index]];
    [colorView setNeedsDisplay:YES];
    [colorView setNeedsLayout:YES];
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    dispatch_async(mainQueue,^{
        [colorView setNeedsDisplay:YES];
        [colorView setNeedsLayout:YES];
        [colorView updateLayer];
        [colorView displayIfNeeded];
        [colorView display];
    });
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
    [NSApp runModalSession:aSession];

我的colorView的绘画代码如下:

- (void)display
{
    CALayer *layer = self.layer;
    [layer setNeedsDisplay];
    [layer displayIfNeeded];
}
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context
{
    [self internalDrawWithRect:self.bounds];
}
- (void)internalDrawWithRect:(CGRect)rect
{
    NSRect bounds = [self bounds];
    [color set];
    [NSBezierPath fillRect:bounds];
}
 - (void)drawRect:(CGRect)rect {
    [self internalDrawWithRect:rect];
}

任何帮助都将非常受欢迎!我的原始代码要简单得多,但是我不断添加可能有所帮助的东西。

1 个答案:

答案 0 :(得分:0)

正如我所说,原始代码相当简单明了: 测量回路:

for ( uint32 index = 0; index < numberOfColors && !stopMeasuring; index++ )
{
    #ifndef NDEBUG
    NSLog( @"Color on screen:%@", [colorsForMeasuring objectAtIndex:index] );
    #endif

    [colorView setColor:[colorsForMeasuring objectAtIndex:index]];
    [colorView setNeedsDisplay:YES];
    [colorView displayIfNeeded];

    // Measure the displayed color in XYZ values
    CGFloat myRed, myGreen, myBlue, myAlpha;
    [[colorsForMeasuring objectAtIndex:index] getRed:&myRed green:&myGreen blue:&myBlue alpha:&myAlpha];
    float theR = (float) myRed;
    float theG = (float) myGreen;
    float theB = (float) myBlue;
    xyzData = [measDeviceController measureOnceXYZforRed:255.0f*theR Green:255.0f*theG Blue:255.0f*theB];
    if ( [xyzData count] > 0 )
    {
        measuringResults[index*3]           = [[xyzData objectAtIndex:0] floatValue];
        measuringResults[(index*3) + 1] = [[xyzData objectAtIndex:1] floatValue];
        measuringResults[(index*3) + 2] = [[xyzData objectAtIndex:2] floatValue];
        #ifndef NDEBUG
        printf("Measured value X=%f, Y=%f, Z=%f\n", measuringResults[index*3], measuringResults[(index*3) + 1], measuringResults[(index*3) + 2]);
        #endif
    } }

从NSView继承而来的MCTD_ColorView的图形:

- (void)setColor:(NSColor *)aColor;
{
    [aColor retain]; 
    [color release]; 
    color = aColor;
}

- (void)drawRect:(NSRect)rect
{
    NSRect bounds = [self bounds];
    [color set];
    [NSBezierPath fillRect:bounds];
}
- (void)dealloc
{
    [color release];
    [super dealloc];
}

在运行测量循环并将断点放置在“ setColor”和“ drawRect”中之后,调试始终在setColor中停止,但永远不会在drawRect中停止。如果不进行调试,该视图将保持白色,同时我应该看到所有不同的颜色出现了。

从我的第一篇文章中可以看出,我已经尝试了很多方法来绘制它,但是都失败了。