iOS View 转换图片

2018-12-20  本文已影响34人  AZander

iOS View 转换图片

可采用以下几种方法

    func snapshotHierarchy() -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, true, scaleHight())
        self.drawHierarchy(in: self.bounds, afterScreenUpdates: true)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
    @available(iOS 10.0, *)
    func snapshotFromRender() -> UIImage? {
        let renderer = UIGraphicsImageRenderer.init(size: self.bounds.size)
        let image = renderer.image {[weak self] (context) in
            
            return self?.layer.render(in: context.cgContext)
        }
        return image
    }
   func snapshotFromContext(scale:CGFloat) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, scale)//UIScreen.main.scale
        guard let ctx = UIGraphicsGetCurrentContext() else { return nil }
        self.layer.render(in: ctx)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
 func snapshotAdapted() -> UIImage? {
        guard self.bounds.size.height > 0 && self.bounds.size.width > 0 else { return nil }
        if #available(iOS 10, *) {
            return snapshotFromRender()
        } else {
            return snapshotFromContext(scale: 0.0)
        }
    }

参考

其他基础概念

设备坐标系(CGContext中使用的坐标系)和用户坐标系(UIKit如UIView、CALayer的Frame使用的坐标系)

Image的Size、scale、pixel与显示

坐标系的转换

难点和问题

上一篇下一篇

猜你喜欢

热点阅读