iOS View 转换图片
可采用以下几种方法
- 1、UIView的drawHierarchy方法 (Used when simple hierarchy)
func snapshotHierarchy() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, true, scaleHight())
self.drawHierarchy(in: self.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
- 2、UIGraphicsImageRenderer方法(iOS10新增的方法,iPhone7及其以上设备采用广色域屏幕及16位色域(16 color gamut))
@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
}
- 3、CALayer的render方法
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)
}
}
- 图层遍历绘制在上下文中绘制image(ImageView的Image或者UIView生成的Image)(待续)
参考
其他基础概念
设备坐标系(CGContext中使用的坐标系)和用户坐标系(UIKit如UIView、CALayer的Frame使用的坐标系)
Image的Size、scale、pixel与显示
坐标系的转换
-
方法一
context.scaleBy(x: 1.0, y: -1.0) context.translateBy(x: 1.0, y: viewContentBg.bounds.size.height)
-
方法二
context.rotate(by: CGFloat.pi) context.scaleBy(x: -1, y: 1) context.translateBy(x: 0, y: CGFloat(-viewContentBg.bounds.size.height))
难点和问题
- 绘制图片设置transfer
网友评论