在 Swift 中,可以使用 'UIView' 的 'drawHierarchy(in:afterScreenUpdates:)' 方法将 'UIView' 转换为 'UIImage'。下面是一个示例代码:

extension UIView {
    func toImage() -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0.0)
        defer { UIGraphicsEndImageContext() }
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        layer.render(in: context)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        return image
    }
}

// 使用示例
let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
view.backgroundColor = .red

if let image = view.toImage() {
    // 使用转换后的 UIImage
    let imageView = UIImageView(image: image)
}

在上面的示例中,我们扩展了 'UIView' 类,添加了一个 'toImage()' 方法,该方法使用当前视图的上下文将其转换为 'UIImage'。然后,你可以将转换后的 'UIImage' 用作 'UIImageView' 的图像或进行其他操作。

Swift: 如何将 UIView 转换为 UIImage

原文地址: https://www.cveoy.top/t/topic/qAxf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录