在我看来,我的 subview 很少。这是 UIImageView。
每个 UIImageView 都包含带有 alpha channel 的图像。
这是一张图片:
我使用下面的方法来检测位置 View 中的触摸:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self.view];
NSArray *views = [self.view subviews];
for (UIView *v in views) {
if([v isKindOfClass:[Piece class]]){
if (CGRectContainsPoint(v.frame, touchLocation) && ((Piece *)v).snapped == FALSE) {
UITouch* touchInPiece = [touches anyObject];
CGPoint point = [touchInPiece locationInView:(Piece *)v];
BOOL solidColor = [self verifyAlphaPixelImage:(Piece *)v atX:point.x atY:point.y];
if (solidColor) {
dragging = YES;
oldX = touchLocation.x;
oldY = touchLocation.y;
piece = (Piece *)v;
[self.view bringSubviewToFront:piece];
break;
}
}
}
}
}
以及此验证 alpha 像素的方法
- (BOOL)verifyAlphaPixelImage:(Piece *)image atX:(int)x atY:(int)y{
CGImageRef imageRef = [image.image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = malloc(height * width * 4);
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 * y) + x * bytesPerPixel;
// CGFloat red = (rawData[byteIndex] ) ;
// CGFloat green = (rawData[byteIndex + 1] ) ;
// CGFloat blue = (rawData[byteIndex + 2] ) ;
CGFloat alpha = (rawData[byteIndex + 3] ) ;
NSLog(@"%f", alpha);
free(rawData);
if(alpha==255.0) return NO;
else return YES;
}
如果建立了alpha像素,我需要触摸我之前有tapp的UIImageView下面的其他UIImageView。
例如,如果我堆叠了 UIImageView 并且我首先触摸:
现在我应该首先验证 UIImageView
如果我触及 alpha 像素 -> 我应该使用此坐标移动到下一个 UIImageView 并验证它的 alpha 像素。
如果第二个、第三个、第四个或第五个没有我的坐标的 alpha 像素,我应该选择这个 UIImageView。
现在我验证我的像素 - 但我的方法返回错误的值。
最佳答案
- 在 How to get pixel data from a UIImage (Cocoa Touch) or CGImage (Core Graphics)? 的讨论中,有一个修正 你正在使用的常规。使用 calloc 而不是 malloc,否则你就会开始 得到任意结果。
- 如果您的
Piece
类曾经缩放图像,您将需要根据图像显示的比例来缩放其 x 和 y 输入。 touchesBegan
方法奇怪地查看它包含的其他 View ,而不是它本身。是否有一个原因?touchesBegan
属于哪个类?- subview 按从后到前的绘制顺序存储,因此当您迭代 subview 时,您将首先查看(并可能选择)最后面的对象。相反,从
subview
的最后一个元素向前迭代。 - 即使这样工作后,效率也会非常低,每次用户点击时都会渲染每个 Piece 图像。您最终会希望缓存每个片段的像素数据以便快速查找。
关于ios - 使用坐标验证像素 (iOS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10067616/