[英]Swift - After Screen Updates - UIView to UIImage Conversion
我正在尝试创建一个UIImage
,该图像将用于设置UICollectionViewCell
的背景。 我发现此功能可以将UIView
转换为UIImage
:
func imageWithView(view: UIView) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0.0)
view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
let snapshotImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return snapshotImage
}
在集合视图单元格函数中,我执行以下操作:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! VideoCell
//creating view
let colour1 = UIColor.yellow.cgColor
let colour2 = UIColor.red.cgColor
let gradientLayer = CAGradientLayer()
gradientLayer.frame = contentView.bounds
gradientLayer.colors = [colour1, colour2]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
let gradientView = UIView(frame: contentView.bounds)
gradientView.layer.addSublayer(gradientLayer)
//converting UIView to UIImage
let ccimage = imageWithView(view: gradientView)
}
但是,我不断收到此错误:
不支持在CoreAnimation提交内使用afterScreenUpdates:YES查看(0x7fe876e2d940,UIView)绘图
如果我执行afterScreenUpdates: false
,那么我会收到此错误:
[快照]绘制至少一次未渲染的视图需要afterScreenUpdates:是。
我真的很困惑如何解决这个错误。 我在错误的地方调用了函数吗?
尝试一下这是它的工作代码(速记4)
在UICollectionView中的cellForItemAt
方法。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! VideoCell
//creating view
let colour1 = UIColor.yellow.cgColor
let colour2 = UIColor.red.cgColor
let gradientLayer = CAGradientLayer()
gradientLayer.frame = contentView.bounds
gradientLayer.colors = [colour1, colour2]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
let gradientView = UIView(frame: contentView.bounds)
gradientView.layer.addSublayer(gradientLayer)
//converting UIView to UIImage
if cell.backgroundColor == nil{
cell.backgroundColor = UIColor(patternImage:gradientView.gradient_image!)
}
return cell
}
将UIView
转换为UIImage
扩展
extension UIView {
var gradient_image: UIImage? {
if #available(iOS 10.0, *) {
let renderer = UIGraphicsImageRenderer(bounds: bounds)
return renderer.image { rendererContext in
layer.render(in: rendererContext.cgContext)
}
} else {
// If Swift version is lower than 4.2,
UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0.0)
defer { UIGraphicsEndImageContext() }
guard let currentContext = UIGraphicsGetCurrentContext() else {
return nil
}
self.layer.render(in: currentContext)
return UIGraphicsGetImageFromCurrentImageContext()
}
}
}
输出:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.