我正在尝试截取UIImageview对象覆盖的区域的屏幕快照。我已经用一些UILabel对象覆盖了图像,并且只想保存该区域的镜头
我尝试过
UIGraphicsBeginImageContext(self.view.frame.size)
view.drawHierarchy(in: self.view.frame, afterScreenUpdates: true)
let memedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
但这给了我整个屏幕的画面
我也尝试过
UIGraphicsBeginImageContext(imageHolder.frame.size)
view.drawHierarchy(in: self.view.frame, afterScreenUpdates: true)
let memedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
这给了我屏幕上半部的矩形
答案 0 :(得分:2)
如果将UILabel
作为子视图添加到UIImageView
,则可以使用类似的扩展功能来捕获图像视图及其子视图(标签)的图像上下文。
extension UIImageView {
func renderSubviewsToImage() -> UIImage? {
guard let image = image else { return nil }
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(image.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
self.layer.render(in: context)
let renderedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return renderedImage
}
}
答案 1 :(得分:1)
view.drawHierachy实际上接受边界作为边界而不是框架 我将假定图像实际上是UIImageView
var bounds= CGRect(x: -image.frame.minX,y: -image.frame.minY,width: view.bounds.size.width,height: view.bounds.size.height)
UIGraphicsBeginImageContext(image.frame.size)
view.drawHierarchy(in: bounds, afterScreenUpdates: true)
let outputImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()