【发布时间】:2013-05-23 20:05:54
【问题描述】:
我正在开发一个 iPad 应用程序,它在 viewcontoller 中有多个 UIImageViews。每个图像都有一些透明部分。当用户点击我想测试的图像时,如果他点击的图像区域不透明,那么我想做一些动作
经过搜索,我得出结论,我必须访问图像的原始数据并检查用户点击的点的 alpha 值
我使用了here 中的解决方案,它帮助很大。我修改了代码,如果用户单击的点是透明的(alpha 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);
}
提前谢谢你
【问题讨论】: