【发布时间】:2009-11-20 22:57:23
【问题描述】:
我在 png 文件中有图像,例如 this。我加载它并在 drawRect 方法中绘制。我可以在 iPhone 上更改 Core Graphics 或 Quartz 中的图像颜色吗?我想要红色的足球,而不是黑色的。可以吗?
【问题讨论】:
标签: iphone cocoa core-graphics
我在 png 文件中有图像,例如 this。我加载它并在 drawRect 方法中绘制。我可以在 iPhone 上更改 Core Graphics 或 Quartz 中的图像颜色吗?我想要红色的足球,而不是黑色的。可以吗?
【问题讨论】:
标签: iphone cocoa core-graphics
您链接的图像是具有白色背景的图像,这使它有点诡计(尽管可能有一种方法可以使我找不到的特定颜色清晰)。一种方法是获取图像的位图表示并遍历每个像素以更改颜色。
这些示例不能直接在 iPhone 上运行,但可以作为您想要做的事情的起点。
在第一个中,它只是遍历像素并将所有非白色像素更改为红色。除非您要更改的颜色始终为黑色,否则您可能希望将颜色着色,而不是将其设置为全红色。
NSImage *image = [NSImage imageNamed:@"football.jpg"];
NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithData:[image TIFFRepresentation]];
NSSize imageSize = [bitmap size];
int samples = imageSize.height * [bitmap bytesPerRow];
unsigned char *bitmapData = [bitmap bitmapData];
int samplesPerPixel = [bitmap samplesPerPixel];
int startSample = [bitmap bitmapFormat] & NSAlphaFirstBitmapFormat ? 1 : 0;
for (int i = startSample; i < samples; i = i + samplesPerPixel) {
if (bitmapData[i] < 255.0 && bitmapData[i + 1] < 255.0 && bitmapData[i + 2] < 255.0) {
bitmapData[i] = 255.0;
}
}
NSImage *newImage = [[NSImage alloc] initWithSize:[bitmap size]];
[newImage addRepresentation:bitmap];
[bitmap release];
如果您可以控制源图像,则使用透明背景创建它们并将它们保存为 PNG(或其他支持 alpha 通道的格式)可能会更容易。至少使用 AppKit,您可以做一个更简单的解决方案。
NSImage *image = [NSImage imageNamed:@"football-transparent.png"];
NSSize size = [anImage size];
NSRect imageBounds = NSMakeRect(0, 0, size.width, size.height);
NSImage *newImage = [anImage copy];
[newImage lockFocus];
[[NSColor redColor] set];
NSRectFillUsingOperation(imageBounds, NSCompositeSourceAtop);
[newImage unlockFocus];
【讨论】:
NSRectFillUsingOpperation 等效的东西。