我的目标如下。
当玩家触摸屏幕时,程序应该找出触摸位置的像素值,然后循环遍历每个像素,任何具有完全相同 RGBA 值的像素都将被编辑,此时我只想设置alpha 为 0 以使它们全部不可见。
到目前为止,我已经设法检索信息,找出哪些对应于触摸的像素,但是当我设置像素并从新数据创建 UIImage 并设置它时。没有什么变化。
一点帮助将不胜感激。
代码如下
功能
(UIImage*)getRGBAsFromImage:(UIImage*)image atX:(int)xx andY:(int)yy
// First get the image into your data buffer
CGImageRef imageRef = [image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
//convert phone screen coords to texture coordinates.
xx *= width/[[UIScreen mainScreen] bounds].size.width;
yy *= height/[[UIScreen mainScreen] bounds].size.height;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height,
bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);
/* MY STUFF */
int counter = 0;
/* MY STUFF */
// Now your rawData contains the image data in the RGBA8888 pixel format.
// Get the byteIndex of pixel tapped.
int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel;
CGFloat red = (rawData[byteIndex] * 1.0) / 255.0;
CGFloat green = (rawData[byteIndex + 1] * 1.0) / 255.0;
CGFloat blue = (rawData[byteIndex + 2] * 1.0) / 255.0;
CGFloat alpha = (rawData[byteIndex + 3] * 1.0) / 255.0;
byteIndex += 4;
for(int x = 0; x < width; x++)
{
for(int y = 0; y < height; y++)
{
byteIndex = (x + (y * width)) * bytesPerPixel;
CGFloat redVal = ( rawData[byteIndex] * 1.0) / 255.0;
CGFloat greenVal = ( rawData[byteIndex + 1] * 1.0) / 255.0;
CGFloat blueVal = ( rawData[byteIndex + 2] * 1.0) / 255.0;
CGFloat alphaVal = ( rawData[byteIndex + 3] * 1.0) / 255.0;
byteIndex += 4;
if( alphaVal != 0 )
{
if( redVal == red && greenVal == green && blueVal == blue )
{
rawData[byteIndex] = 255;
rawData[byteIndex + 1] = 255;
rawData[byteIndex + 2] = 255;
rawData[byteIndex + 3] = 1;
counter ++;
}
}
}
}
UIImage *newImage = [UIImage imageWithCGImage: imageRef];
image = newImage;
NSLog(@"Pixels amount: %i", counter);
free(rawData);
return image;
它是这样称呼的
tempBGRef.image = [MainMenuViewController getRGBAsFromImage:[tempBGRef image] atX:touchPointInView.x andY:touchPointInView.y];