我正在开发一个在 viewcontoller 中有多个 UIImageViews 的 iPad 应用程序。每个图像都有一些透明部分。当用户单击图像时,我想测试他单击的图像区域是否不透明,然后我想做一些动作
搜索后我得出的结论是我必须访问图像的原始数据并检查用户单击的点的 alpha 值
我使用了在这里找到的解决方案,它有很大帮助。我修改了代码,以便如果用户单击的点是透明的(alpha <1),则 prent 0 否则打印 1。但是,结果在运行时不准确。我有时会得到 0,其中单击的点不透明,反之亦然。我认为byteIndex值有问题我不确定它是否会在用户单击时返回颜色数据
这是我的代码
CGPoint touchPoint;
- (void)viewDidLoad
{
[super viewDidLoad];
[logo addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)]];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
touchPoint = [touch locationInView:self.view];
}
- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer
{
int x = touchPoint.x;
int y = touchPoint.y;
[self getRGBAsFromImage:img atX:x andY:y];
}
- (void)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);
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);
// Now your rawData contains the image data in the RGBA8888 pixel format.
int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel;
CGFloat alpha = (rawData[byteIndex + 3] * 1.0) / 255.0;
byteIndex += 4;
if (alpha < 1) {
NSLog(@"0");
// here I should add the action I want
}
else NSLog(@"1");
free(rawData);
}
提前谢谢你