我正在尝试截取屏幕的屏幕截图并从该屏幕截图中裁剪一部分。屏幕截图部分工作正常,但我无法使裁剪部分正常工作。
var image = self.view?.pb_takeSnapshot()
let croprect = CGRectMake(view.bounds.width/2, view.bounds.height/3.8,
view.bounds.width/2, view.bounds.height/3.5)
var imageRef = CGImageCreateWithImageInRect(CGImage(image), croprect) //Error: CGImage cannot be constructed because it has no accessible initializers
var croppedImage = UIImage(CGImage: imageRef)
截取屏幕截图的函数:
func pb_takeSnapshot() -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, UIScreen.mainScreen().scale);
self.drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)
// old style: self.layer.renderInContext(UIGraphicsGetCurrentContext())
let image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
我的问题:有没有办法在不使用CGImage的情况下做到这一点,或者有没有一种简单的方法可以将UIImage转换为CGImage?
在大多数情况下
,UIImage
包含一个可以直接访问的CGImage
。
在您的情况下,image
是使用可选链接设置的,并且属于 UIImage?
类型,因此您需要:
UIImage?.CGImage
访问CGImage