سؤال

CGContextRef ctx = CGContextRetain([[NSGraphicsContext currentContext] graphicsPort]);
CGColorRef color = CGColorRetain([NSColor colorWithCalibratedRed:0 green:0 blue:0 alpha:0.5f].CGColor);

CGContextSaveGState(ctx);
{
    CGContextSetFillColorWithColor(ctx, color);
    CGContextFillRect(ctx, dirtyRect);
}
CGContextRestoreGState(ctx);

CGColorRelease(color);
CGContextRelease(ctx);
هل كانت مفيدة؟

المحلول

Like the error message says, NSColor objects don't respond to CGColor messages in Lion—that method was added in 10.8. On 10.7, you will have to convert the NSColor to a CGColor yourself.

Here's a function that does the conversion. On 10.8, it just returns the NSColor's CGColor. If that isn't available, it does the conversion itself.

CGColorRef PRHCreateCGColorWithNSColor(NSColor *color) {
    if ([color respondsToSelector:@selector(CGColor)]) {
        CGColorRef cgColor = [color CGColor];
        return cgColor != NULL ? (CGColorRef)CFRetain(cgColor) : NULL;
    }

    NSString *colorSpaceName = [color colorSpaceName];
    NSColorSpace *colorSpaceNS;
    if ([colorSpaceName isEqualToString:NSNamedColorSpace] || [colorSpaceName isEqualToString:NSPatternColorSpace]) {
        colorSpaceNS = [NSColorSpace genericRGBColorSpace];
        color = [color colorUsingColorSpace:colorSpaceNS];
    } else {
        colorSpaceNS = [color colorSpace];
    }
    CGColorSpaceRef colorSpace = [colorSpaceNS CGColorSpace];

    size_t numberOfComponents = CGColorSpaceGetNumberOfComponents(colorSpace);
    CGFloat components[numberOfComponents];
    [color getComponents:components];

    return CGColorCreate(colorSpace, components);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top