裁剪UIImage。裁剪后的图像不正确

时间:2014-05-01 02:27:45

标签: ios

我在屏幕上有一个UIImageView。它显示多种颜色的图像。当我点击图像时,它会裁剪图像的一小部分,并将裁剪后的图像设置为新的小UIImageView。由于某种原因,裁剪的图像总是错误的。看看下面的截图:

enter image description here

以下是touchesBegin的完整代码:

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGPoint location = [[touches anyObject] locationInView:self.imageView];

    UIImage *originalImage = self.imageView.image;

    NSLog(@"x = %f, y = %f",location.x,location.y);

    CGRect cropRegion = CGRectMake(location.x, location.y, 10, 10);

    CGImageRef subImage = CGImageCreateWithImageInRect(originalImage.CGImage, cropRegion);

    UIImage *croppedImage = [UIImage imageWithCGImage:subImage scale:originalImage.scale orientation:originalImage.imageOrientation];

    [self.previewImageView setImage:croppedImage];

    CGImageRelease(subImage);

}

1 个答案:

答案 0 :(得分:2)

最可能的解释是图像尺寸大于视图尺寸,因此图像缩小以适合视图。结果是视图坐标与图像坐标不匹配,因此locationInView返回的点不能直接用于CGImageCreateWithImageInRect

要解决此问题,您需要根据self.imageView.bounds.sizeoriginalImage.size确定x和y比例因子,然后相应地缩放location