如何从 scaleAspectFit 模式的 UIImageView 的 UIImage 获取快照?

How to take a snapshot from UIImage of a UIImageView that is scaleAspectFit mode?

我在 UIImageView:

中有一张图片
imageView.contentMode = .scaleAspectFit        
imageView.backgroundColor = .red

因为 .scaleAspectFit 图像视图有一些红色边框,没关系:

用户可以在 imageView 上添加一些 UIView 之类的标签或图片。 在最后一步,我使用以下代码保存编辑后的图像,用户可以共享它或将其保存到照片库:

private func generateImage() -> UIImage? {
    var finalImage: UIImage?
    UIGraphicsBeginImageContextWithOptions(CGSize(width: imageView.frame.size.width, height: imageView.frame.size.height), true, 0)
    imageView.drawHierarchy(in: CGRect(x: 0, y: 0, width: imageView.frame.size.width, height: imageView.frame.size.height), afterScreenUpdates: true)
    finalImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}

问题是 finalImage 仍然有 imageView 的红色边框。

您可以在 AspectFit 内容模式的 UIImageView 中显示 UIImageCGRect。请像这样创建 UIImageView 的扩展,

extension UIImageView {
    var contentClippingRect: CGRect {
        guard let image = image else { return bounds }
        guard contentMode == .scaleAspectFit else { return bounds }
        guard image.size.width > 0 && image.size.height > 0 else { return bounds }

        let scale: CGFloat
        if image.size.width > image.size.height {
            scale = bounds.width / image.size.width
        } else {
            scale = bounds.height / image.size.height
        }

        let size = CGSize(width: image.size.width * scale, height: image.size.height * scale)
        let x = (bounds.width - size.width) / 2.0
        let y = (bounds.height - size.height) / 2.0

        return CGRect(x: x, y: y, width: size.width, height: size.height)
    }
}

您现在可以使用imageView.contentClippingRect阅读如何读取里面图像的位置和大小。

你必须对你的方法做一些小的改变,用适当的边界调用你的函数,如 contentClippingRect

如有任何疑问,请告诉我。

更新

请试试这个 UIImageView+Extension,这可能对你有帮助。在Objective-C代码中,转换成Swift.

你也可以试试这个,

    let image  = #imageLiteral(resourceName: "Cat03")
    let x: CGRect = AVMakeRect(aspectRatio: image.size, insideRect: imageView1.frame)
    print(x)

以上代码为您提供了完美的尺寸。