首页 > 解决方案 > 为什么截图图像被拉伸了?

问题描述

我正在使用UIGraphicsBeginImageContextWithOptions自定义CGSize我不知道为什么我得到拉伸图像?

UIGraphicsBeginImageContextWithOptions(CGSize(width: UIScreen.main.bounds.width, height: 200) , false, 0)
let cellRect = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 200)
view.drawHierarchy(in: cellRect, afterScreenUpdates: true)
let wholeImage = UIGraphicsGetImageFromCurrentImageContext()//stretched image
UIGraphicsEndImageContext()

标签: iosswiftuiimagexcode9

解决方案


您将图像上下文设置为 200 的高度,但随后您对单元格 rect 执行相同操作,这意味着它将截取整个屏幕截图并将其放入 (screenWidth, 200) 帧中。您需要保留 200 的上下文,然后仅view.bounds用于 cellRect ,200 px如果这是您需要的,您应该获得视图的顶部。

UIGraphicsBeginImageContextWithOptions(CGSize(width: UIScreen.main.bounds.width, height: 200) , false, 0)
let cellRect = self.view.bounds
self.view.drawHierarchy(in: cellRect, afterScreenUpdates: true)
let wholeImage = UIGraphicsGetImageFromCurrentImageContext()//stretched image
UIGraphicsEndImageContext()

推荐阅读