首页 > 解决方案 > 如何在 swift 4 或更高版本中裁剪具有可选区域的图像?

问题描述

我需要一些关于我想在我的应用程序中实现的功能的帮助。我在 Aspect Fit 中有一个带有内容模式的图像视图的视图。当我从我的库中获取图像时,我想用可调整的矩形裁剪一个区域,创建一个新图像。我一直在寻找一些示例或在线教程,但没有成功。任何人都可以帮助我吗?这是我的视图中的图像。

这是我在故事板中的观点.

这是我在模拟器中的看法

标签: uiimageviewuiimageswift4

解决方案


简单的解决方案是在特定的范围内渲染图像视图CGRect

func snapshot(in imageView: UIImageView, rect: CGRect) -> UIImage {
    return UIGraphicsImageRenderer(bounds: rect).image { _ in
        imageView.drawHierarchy(in: imageView.bounds, afterScreenUpdates: true)
    }
}

这种方法的局限性在于,如果图像的分辨率比图像视图可以渲染的分辨率高很多(当我们使用“aspect scale fit”时经常出现这种情况),您将失去这种额外的精度。

如果你想保持分辨率,你应该将CGRect坐标转换为图像的坐标,在这种情况下,假设“纵横比适合”(即居中并缩放,以便显示整个图像):

func snapshot(in imageView: UIImageView, rect: CGRect) -> UIImage {
    assert(imageView.contentMode == .scaleAspectFit)

    let image = imageView.image!

    // figure out what the scale is

    let imageRatio = imageView.bounds.width / imageView.bounds.height
    let imageViewRatio = image.size.width / image.size.height

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

    // convert the `rect` into coordinates within the image, itself

    let size = rect.size * scale
    let origin = CGPoint(x: image.size.width  / 2 - (imageView.bounds.midX - rect.minX) * scale,
                         y: image.size.height / 2 - (imageView.bounds.midY - rect.minY) * scale)
    let scaledRect = CGRect(origin: origin, size: size)

    // now render the image and grab the appropriate rectangle within
    // the image’s coordinate system

    let format = UIGraphicsImageRendererFormat()
    format.scale = image.scale
    format.opaque = false

    return UIGraphicsImageRenderer(bounds: scaledRect, format: format).image { _ in
        image.draw(at: .zero)
    }
}

使用这个扩展:

extension CGSize {
    static func * (lhs: CGSize, rhs: CGFloat) -> CGSize {
        return CGSize(width: lhs.width * rhs, height: lhs.height * rhs)
    }
}

这会产生:

在此处输入图像描述


推荐阅读