当前的Context始终为零

时间:2018-04-12 14:51:53

标签: ios uiview

目前的上下文始终为零

扩展名UIView {     var screenShotImage:UIImage? {

    UIGraphicsBeginImageContextWithOptions( self.bounds.size, true, 0 )
    guard let context = UIGraphicsGetCurrentContext() else {
         UIGraphicsEndImageContext()
        print("Context equal nil")
            return nil
            }
    context.translateBy(x: -bounds.origin.x, y: -bounds.origin.y)
    layer.render(in: context)
    guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
         UIGraphicsEndImageContext()
        print("fail to take view shot")
            return nil
    }
    UIGraphicsEndImageContext()
    return image
}

1 个答案:

答案 0 :(得分:0)

您是否介意将Computed Property内的extension更改为instance method声明,如下所示

import UIKit
extension UIView {

    func getScreenshot() -> UIImage? {
        UIGraphicsBeginImageContextWithOptions( self.bounds.size, true, 0 )
        guard let context = UIGraphicsGetCurrentContext() else {
            UIGraphicsEndImageContext()
            print("Context equal nil")
            return nil
        }
        context.translateBy(x: -bounds.origin.x, y: -bounds.origin.y)
        layer.render(in: context)
        guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
            UIGraphicsEndImageContext()
            print("fail to take view shot")
            return nil
        }
        UIGraphicsEndImageContext()
        return image
    }
}

哪个工作正常。这个Question简要解释了原因。