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

标签 swift uiimageview uiimage

我在 UIImageView 中有一张图片:

imageView.contentMode = .scaleAspectFit        
imageView.backgroundColor = .red

因为 .scaleAspectFit ImageView 有一些红色边框,这没关系:

imageView with .scaleAspectFit image

用户可以在 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)

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

关于swift - 如何从 scaleAspectFit 模式的 UIImageView 的 UIImage 获取快照?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50148987/

相关文章:

ios - 无法使用 Swift 工作 GLKView

ios - 如何使用 swift 在 Xcode 中设置背景图片?

ios - 如何让 SwiftUI View 扩大可用空间?

ios - 更改场景时出错。( SpriteKit )

ios - UIImageView 没有专注于 tvOS

ios - 尽可能压缩UIImage?

ios - 覆盖 UIImage(名为 : )

IOS Swift SDWebImage 不编码 URL,如何为其设置编码器?

ios - 快速将手势添加到 UIImageView?

iOS 在 UIImage 上动画蒙版