Objective-C / iPhone - 如何改变像素颜色?

3

我的项目目标是:用户可以通过触摸屏幕来更改图像的某个部分的颜色,当他触摸任何区域时,该区域的颜色应该被更改。

我有很多想法,但它们都基于在视图中放置另一个图像(动态创建),但是这些想法会消耗大量内存;

如何实现这一点 ()。

1个回答

5
您可以使用核心图形(Core Graphics)进行操作。将QuartzCore框架添加到您的项目中。
最基本的方法是在位图上下文中呈现您的图像:
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef bmContext = CGBitmapContextCreate(NULL, width, height, 8,bytesPerRow, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = originalWidth, .size.height = originalHeight}, cgImage);

那么你可以获取对底层像素的引用:
UInt8* data = (UInt8*)CGBitmapContextGetData(bmContext);

然后进行像素操作:
const size_t bitmapByteCount = bytesPerRow * originalHeight;
for (size_t i = 0; i < bitmapByteCount; i += 4)
{
    UInt8 a = data[i];
    UInt8 r = data[i + 1];
    UInt8 g = data[i + 2];
    UInt8 b = data[i + 3];

    // Do pixel operation here

    data[i] = (UInt8)newAlpha
    data[i + 1] = (UInt8)newRed;
    data[i + 2] = (UInt8)newGreen;
    data[i + 3] = (UInt8)newBlue;
}

最后从上下文中获取您的新图像:
CGImageRef newImage = CGBitmapContextCreateImage(bmContext);

你能否再澄清一些?因为我没有做过这种项目(图形),而且我对核心图形也很新,我已经尝试了一些编码,但不幸的是它没有起作用。 - Mouhamad Lamaa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接