CGRect裁剪图像显示错误的值

时间:2014-06-06 18:37:04

标签: ios objective-c cgrect

当我尝试裁剪图像的底部时,结果从左上角放大。如果没有裁剪,图像显示就好了。我真的无法通过裁剪功能看到我在这里做错了什么。为什么这不能用作物返回完整的图像?请参阅下面的代码和结果:

- (UIImage *)croppedImageFromScreenShot
{
    // Prepare view for screen capture

    // Screen Capture

    CGRect fullScreenRect = self.view.bounds;

    UIGraphicsBeginImageContextWithOptions(fullScreenRect.size, NO, [UIScreen mainScreen].scale);

    [self.view drawViewHierarchyInRect:fullScreenRect afterScreenUpdates:YES];

    UIImage *screenShotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    // Crop Image

    CGFloat cropDistance = 20.0;

    CGSize imageSize = screenShotImage.size;

    CGRect imageRect = CGRectMake(0.0, 0.0, imageSize.width, imageSize.height);

    CGRect cropRect = CGRectInset(imageRect, 0.0, cropDistance);

    CGImageRef imageRef = CGImageCreateWithImageInRect([screenShotImage CGImage], cropRect);

    UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];

    CGImageRelease(imageRef);

    // Restore view after screen capture


    return croppedImage;
}

裁剪效果很好,但图像放大并缩小:

enter image description here

如果没有裁剪,下面的代码就可以了。

- (UIImage *)croppedImageFromScreenShot
{
    // Prepare view for screen capture

    // Screen Capture

    CGRect fullScreenRect = self.view.bounds;

    UIGraphicsBeginImageContextWithOptions(fullScreenRect.size, NO, [UIScreen mainScreen].scale);

    [self.view drawViewHierarchyInRect:fullScreenRect afterScreenUpdates:YES];

    UIImage *screenShotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();


    return screenShotImage;
}

返回原始图像,因为它也应该与裁剪功能一起使用:

enter image description here

2 个答案:

答案 0 :(得分:1)

您正在处理视网膜显示器上的缩放图像,但使用屏幕坐标来确定最终图像尺寸(非视网膜)。因此,这会让您左上角,减去您使用插入框架移除的框架。通过[UIScreen mainScreen] .scale将imageSize.width和imageSize.height相乘,你可能会得到你原来的样子。

CGSize imageSize = screenShotImage.size;
imageSize.width *= [UIScreen mainScreen].scale;
imageSize.height *= [UIScreen mainScreen].scale;

为了只删除图像的底部,请尝试使用此代替CGRectInset:

CGRect cropRect = imageRect;
cropRect.size.height -= cropDistance;

答案 1 :(得分:1)

改变这个:

CGRect cropRect = CGRectInset(imageRect, 0.0, cropDistance);

分为:

CGRect cropRect = CGRectMake(0,0,imageSize.width, imageSize.height - cropDistance);

您只想将所需的特定矩形定义为图像的子集,因此如果要裁剪底部,则只需从高度中减去。