我正在制作一个 tvOS 应用程序,我希望它看起来与电影应用程序类似。因此我有一个 UICollectionView。现在我的单元格不仅仅是简单的 UIImageView,而是更加复杂。
我仍然希望拥有漂亮的焦点视觉效果(使单元格图像更大,并在用户滑动 Remote 时在其上产生灯光效果)。所以我想做的是渲染我的单元格,然后拍摄它的快照,然后显示该快照而不是单元格本身。我就是这样做的:
extension UIView {
var snapshot : UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, true, 0.0)
drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
...
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = NSBundle.mainBundle().loadNibNamed("ContentCell", owner: self, options: nil)[0] as! ContentCell
cell.update()
let cellSnapshot = cell.snapshot
let snapshotCell = collectionView.dequeueReusableCellWithReuseIdentifier("SnapshotCell", forIndexPath: indexPath) as! SnapshotCell
snapshotCell.snapshotImageView.image = cellSnapshot
return snapshotCell
}
但是,这只是显示一个黑色单元格。有什么想法我可能做错了什么吗?
最佳答案
你应该看看here
在 Swift 中,它会是这样的:
extension UIView {
var snapshot : UIImage? {
var image: UIImage? = nil
UIGraphicsBeginImageContext(bounds.size)
if let context = UIGraphicsGetCurrentContext() {
self.layer.renderInContext(context)
image = UIGraphicsGetImageFromCurrentImageContext()
}
UIGraphicsEndImageContext()
return image
}
}
关于swift - 拍摄 UICollectionViewCell 的快照,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33388116/