[英]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.