目前的上下文始终为零
扩展名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
}
答案 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简要解释了原因。