Swift从UIView层获取UIImage

时间:2017-08-16 22:56:22

标签: ios swift uiview uiimage calayer

我的UIView中有CAShapeLayers,我希望看到UIImage 所以我尝试通过下面的功能,但在发生错误 UIGraphicsGetCurrentContext()

extension UIView
{
    func getImgFromVyuFnc() -> UIImage
    {
        UIGraphicsBeginImageContext(self.frame.size)

        self.layer.renderInContext(UIGraphicsGetCurrentContext())
        let image = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()
        return image!
    }
}
  

致命错误:在展开Optional值时意外发现nil   2017-08-17 04:17:47.230474 PicPac [1095:488887]致命错误:在展开可选值时意外发现nil

1 个答案:

答案 0 :(得分:3)

如果传递给UIGraphicsBeginImageContext(_)的尺寸在其中一个或两个维度中均为零,那么UIGraphicsGetCurrentContext()会返回nil,因此UIGraphicsGetImageFromCurrentImageContext()也会返回。