我在iPad上有一个png图像,尺寸为1214x1214(并且是视网膜的两倍),并将其设置为位于屏幕坐标(0,-20)的UIImageView。为了在设备旋转/方向更改期间它适合屏幕,我将其设置为Aspect Fit类型。
我想要做的是能够触摸屏幕并读取触摸下方像素的RGB值。我已经实现了一个UIGestureRecognizer并将其绑定到UIImage并成功恢复了坐标。
给我带来麻烦的是我尝试了几种检索RGB值的方法(例如[如何获取iphone上图像上像素的RGB值])1 但我的RGB值看起来好像图像偏斜并映射到UIView上的不同位置。
我的问题是,我怎样才能满足这样的事实:我将UIImageView设置为Aspect Fit,以及设备可能是横向或纵向(颠倒或向上)的事实?
答案 0 :(得分:1)
好的,所以我把它解决了,这可能对那些试图做类似事情的人有所帮助。
我使用此函数从另一个答案计算了图像的缩放大小
-(CGRect)frameForImage:(UIImage*)image inImageViewAspectFit:(UIImageView*)imageView
{
float imageRatio = image.size.width / image.size.height;
float viewRatio = imageView.frame.size.width / imageView.frame.size.height;
if(imageRatio < viewRatio)
{
float scale = imageView.frame.size.height / image.size.height;
float width = scale * image.size.width;
float topLeftX = (imageView.frame.size.width - width) * 0.5;
return CGRectMake(topLeftX, 0, width, imageView.frame.size.height);
}
else
{
float scale = imageView.frame.size.width / image.size.width;
float height = scale * image.size.height;
float topLeftY = (imageView.frame.size.height - height) * 0.5;
return CGRectMake(0, topLeftY, imageView.frame.size.width, height);
}
}
将注册函数作为监听器
取得了接触点CGPoint tapPoint = [sender locationInView:imageMap];
根据我的图像移动位置改变了触摸点
if([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait ||
[UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortraitUpsideDown )
{
// portrait (y has increased, x has stayed the same)
tapPoint.y -= rectScaleSize.origin.y;
}
else
{
// landscape (x has increased, y has stayed the same)
tapPoint.x -= rectScaleSize.origin.x;
}
然后根据图像的原始大小及其纵横比适合大小重新调整
tapPoint.x = (tapPoint.x * imageMap.image.size.width) / rectScaleSize.size.width;
tapPoint.y = (tapPoint.y * imageMap.image.size.height) / rectScaleSize.size.height;
其中imageMap.image是我的原始图像,而rectScaleSize是从frameForImage函数返回的
,最后得到RGB值
CGImageRef image = [imageMap.image CGImage];
NSUInteger width = CGImageGetWidth(image);
NSUInteger height = CGImageGetHeight(image);
// NSLog(@"RGB Image is %d x %d",width,height);
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),image);
CGContextRelease(context);
int byteIndex = (bytesPerRow * (int)tapPoint.y) + (int)tapPoint.x * bytesPerPixel;
int red = rawData[byteIndex];
int green = rawData[byteIndex + 1];
int blue = rawData[byteIndex + 2];
//int alpha = rawData[byteIndex + 3];
NSLog(@"RGB is %d,%d,%d",red,green,blue);
似乎工作得很好,希望它有用。 如果我做了一些非常错误的话,欢迎评论!