您要求的是以下两种方法之一:
NSBitmapRep setColor:atX:y:改变指定坐标处像素的颜色。
NSBitmapRep setPixel:atX:y:将指定坐标处的接收者像素设置为指定的原始像素值。
请注意,这些在 iOS 上不可用。在 iOS 上,这样做的方法似乎是为给定的颜色空间(可能是 RGB)创建像素数据的原始缓冲区,用颜色数据填充它(编写一个小的 setPixel 方法来执行此操作),然后调用 CGImageCreate()像这样:
//Create a raw buffer to hold pixel data which we will fill algorithmically
NSInteger width = theWidthYouWant;
NSInteger height = theHeightYouWant;
NSInteger dataLength = width * height * 4;
UInt8 *data = (UInt8*)malloc(dataLength * sizeof(UInt8));
//Fill pixel buffer with color data
for (int j=0; j<height; j++) {
for (int i=0; i<width; i++) {
//Here I'm just filling every pixel with red
float red = 1.0f;
float green = 0.0f;
float blue = 0.0f;
float alpha = 1.0f;
int index = 4*(i+j*width);
data[index] =255*red;
data[++index]=255*green;
data[++index]=255*blue;
data[++index]=255*alpha;
}
}
// Create a CGImage with the pixel data
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, data, dataLength, NULL);
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGImageRef image = CGImageCreate(width, height, 8, 32, width * 4, colorspace, kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast,
provider, NULL, true, kCGRenderingIntentDefault);
//Clean up
CGColorSpaceRelease(colorspace);
CGDataProviderRelease(provider);
// Don't forget to free(data) when you are done with the CGImage
最后,您可能想要操作已加载到 CGImage 中的图像中的像素。在标题为QA1509 Getting the pixel data from a CGImage object的 Apple Technical Q&A 中有执行此操作的示例代码。