我正在尝试创建一个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
}
在我的 Collection View 单元格函数中,我执行以下操作:
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)
}
但是,我不断收到此错误:
View (0x7fe876e2d940, UIView) drawing with afterScreenUpdates:YES inside CoreAnimation commit is not supported
如果我设置 afterScreenUpdates: false
,则会收到此错误:
[Snapshotting] Drawing a view that has not been rendered at least once requires afterScreenUpdates: YES.
我真的很困惑如何解决这个错误。我是否在错误的位置调用了该函数?
最佳答案
尝试这个它的工作代码(swift 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()
}
}
}
输出:
关于ios - Swift - 屏幕更新后 - UIView 到 UIImage 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52473101/