来自UICollectionView的图像使用renderInContext或drawViewHierarchyInRect都失败

时间:2015-09-23 12:11:10

标签: ios swift

我需要从我的collectionView创建一个图像。

可以使用 renderInContext drawViewHierarchyInRect 来完成。

然而.... 当我使用renderInContext方法时,UISegmentedControls中的所有选定元素都不再有textLabel ....

截图: enter image description here

当我使用drawViewHierarchyInRect方法时,我在设备上获得全白图像(ios8或更高版本)。 (模拟器工作正常)。

这是我的代码:

func imageFromScreen() -> NSData {
    let savedContentOffset = self.collectionView!.contentOffset
    let savedFrame = self.collectionView!.frame
    self.collectionView!.frame.size = self.collectionView!.contentSize
    UIGraphicsBeginImageContextWithOptions(self.collectionView!.contentSize, false, 1.0)

    self.collectionView!.layer.renderInContext(UIGraphicsGetCurrentContext()) // This method does not capture segmented controls correctly
    //self.collectionView!.drawViewHierarchyInRect(self.collectionView!.bounds, afterScreenUpdates: true) // White image on iOS8 & higher...

    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    var imageData = UIImagePNGRepresentation(image)

    // restore previous size and scroll position
    self.collectionView!.frame = savedFrame
    self.collectionView!.contentOffset = savedContentOffset

    return imageData!
}

还有哪些其他选项可用于从我的collectionView生成图像?

0 个答案:

没有答案