开发者

Objective-C / iphone - change Pixel Colour?

开发者 https://www.devze.com 2023-03-26 20:30 出处:网络
the aim of my project: user can change the color of a part to images by touching the screen, when he touch any area the color of this area should be changed

the aim of my project: user can change the color of a part to images by touching the screen, when he touch any area the color of this area should be changed

i have many ideas but my ideas are based on placing another images开发者_Python百科 (created dynamically) in the view, but these ideas are memory expensive;

how to do this ().


You can use Core Graphics. Add QuartzCore framework to your project.

The basic way to do this is to render your image in a bitmap context :

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);

then you can grab a reference to the underlying pixels :

UInt8* data = (UInt8*)CGBitmapContextGetData(bmContext);

Then do pixels operation :

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;
}

Finally grab your new image from the context :

CGImageRef newImage = CGBitmapContextCreateImage(bmContext);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号