要使用 Quartz 修改位图,您可以使用图像初始化 CGContextRef 并使用CGContextDraw...
例程绘制到该上下文。
(我为一个 NSView 子类编写了以下示例代码。它有点低效。如果您使用代码,请将您可以保留在 iVars 中的东西分开。)
- (void)drawRect:(NSRect)dirtyRect
{
//Load an image ...
NSImage* image = [[NSImage alloc] initWithContentsOfFile:@"/Library/Desktop Pictures/Grass Blades.jpg"];
CGImageRef testImage = [[[image representations] objectAtIndex:0] CGImage];
[image release];
CGDataProviderRef dataProvider = CGImageGetDataProvider(testImage);
//... and retrieve its pixel data
CFDataRef imageData = CGDataProviderCopyData(dataProvider);
void* pixels = (void*)CFDataGetBytePtr(imageData);
CGColorSpaceRef colorspace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
//Init a quartz context that uses the pixel data memory as buffer
CGContextRef drawContext = CGBitmapContextCreate(pixels, CGImageGetWidth(testImage), CGImageGetHeight(testImage), CGImageGetBitsPerComponent(testImage), CGImageGetBytesPerRow(testImage), colorspace, CGImageGetBitmapInfo(testImage));
CGContextSetRGBFillColor(drawContext, 0.8, 0.8, 0.8, 1.0);
//Do something with the newly created context
CGContextFillRect(drawContext, CGRectMake(20.0, 20.0, 200.0, 200.0));
CGColorSpaceRelease(colorspace);
CGImageRef finalImage = CGBitmapContextCreateImage(drawContext);
//Draw the modified image to the screen
CGContextDrawImage([[NSGraphicsContext currentContext] graphicsPort], dirtyRect, finalImage);
CFRelease(imageData);
CGImageRelease(finalImage);
CGContextRelease(drawContext);
}