Recently I needed to figure out how to set individual pixel color values in a UIImageView. I couldn't find any example on how to do this, so I thought I'd post how I eventually did it.
The following code snippet takes a UIImageView and sets each pixel in the image to a random color. Not very exciting but it shows one approach to setting individual pixel values.
If anyone knows a better way to do this, or how to improve my code, please post.
The following code snippet takes a UIImageView and sets each pixel in the image to a random color. Not very exciting but it shows one approach to setting individual pixel values.
If anyone knows a better way to do this, or how to improve my code, please post.
Code:
- (void)RandomizePixelColors:(UIImageView *)imageView
{
size_t w = imageView.image.size.width;
size_t h = imageView.image.size.height;
// 4 bytes per pixel
int numBytes = 4 * w * h;
unsigned char* pixelData = (unsigned char*)malloc(numBytes * sizeof(unsigned char));
// This loop sets each pixel as a set of 4 bytes
for(int i = 0; i < numBytes; i += 4)
{
int red = i;
int green = i+1;
int blue = i+2;
int alpha = i+3;
pixelData[red] = (arc4random() % 255);
pixelData[green] = (arc4random() % 255);
pixelData[blue] = (arc4random() % 255);
pixelData[alpha] = 255;
}
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, pixelData, numBytes, NULL);
CGImageRef newImageRef = CGImageCreate (
w,
h,
8,
8*4,
4*w,
colorspace,
kCGBitmapByteOrderDefault,
provider,
NULL,
false,
kCGRenderingIntentDefault
);
imageView.image = [UIImage imageWithCGImage:newImageRef];
CGColorSpaceRelease(colorspace);
CGDataProviderRelease(provider);
CGImageRelease(newImageRef);
}