【问题标题】:CGImageCreateWithImageInRect [duplicate]CGImageCreateWithImageInRect [重复]
【发布时间】:2018-07-12 19:36:23
【问题描述】:

我正在尝试创建一个简单的裁剪应用程序。我有一个覆盖在 UIImage 上的视图,我想仅从覆盖视图的 UIImage 部分裁剪新图像。我用了代码

CGRect cropRect = _cropView.frame;
UIImage *cropImage = [UIImage imageWithData:imageData];
CGImageRef cropped = CGImageCreateWithImageInRect([cropImage CGImage], cropRect);
UIImage *croppedImage = [UIImage imageWithCGImage:cropped];
self.imageView.image = croppedImage;

但它导致了一个意想不到的图像,看起来非常放大,而不是我想要的。如何从视图后面的图像中裁剪出新图像?

【问题讨论】:

    标签: objective-c crop cgimageref


    【解决方案1】:

    CGImage 处理像素,而不是“点”(UIKit 的抽象测量单位)。当裁剪视图的contentScaleFactor大于1时,其像素尺寸将大于其点尺寸。因此,要获得与像素对应的裁剪矩形,您需要将视图frame 的所有坐标和尺寸乘以其contentScaleFactor

    CGRect cropRect = _cropView.frame;
    cropRect.origin.x *= _cropView.contentScaleFactor;
    cropRect.origin.y *= _cropView.contentScaleFactor;
    cropRect.size.width *= _cropView.contentScaleFactor;
    cropRect.size.height *= _cropView.contentScaleFactor;
    

    【讨论】:

    • 我试过这个并没有解决问题。图像仍然过于放大并且逆时针旋转了 90 度
    【解决方案2】:

    也许对你有帮助,

    // Create new image context
    CGSize size = _cropView.frame.size;
    
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
    
    // Create rect for image
    CGRect rect = _cropView.frame;
    
    // Draw the image into the rect
    [existingImage drawInRect:rect];
    
    // Saving the image, ending image context
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    

    【讨论】:

    • 感谢您的回复,但这最终也不起作用。我仍然对我的输出感到很困惑
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-10
    • 2013-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多