uiimageview - 如何在 swift 4 或更高版本中裁剪具有可选区域的图像?
问题描述
我需要一些关于我想在我的应用程序中实现的功能的帮助。我在 Aspect Fit 中有一个带有内容模式的图像视图的视图。当我从我的库中获取图像时,我想用可调整的矩形裁剪一个区域,创建一个新图像。我一直在寻找一些示例或在线教程,但没有成功。任何人都可以帮助我吗?这是我的视图中的图像。
.
解决方案
简单的解决方案是在特定的范围内渲染图像视图CGRect
:
func snapshot(in imageView: UIImageView, rect: CGRect) -> UIImage {
return UIGraphicsImageRenderer(bounds: rect).image { _ in
imageView.drawHierarchy(in: imageView.bounds, afterScreenUpdates: true)
}
}
这种方法的局限性在于,如果图像的分辨率比图像视图可以渲染的分辨率高很多(当我们使用“aspect scale fit”时经常出现这种情况),您将失去这种额外的精度。
如果你想保持分辨率,你应该将CGRect
坐标转换为图像的坐标,在这种情况下,假设“纵横比适合”(即居中并缩放,以便显示整个图像):
func snapshot(in imageView: UIImageView, rect: CGRect) -> UIImage {
assert(imageView.contentMode == .scaleAspectFit)
let image = imageView.image!
// figure out what the scale is
let imageRatio = imageView.bounds.width / imageView.bounds.height
let imageViewRatio = image.size.width / image.size.height
let scale: CGFloat
if imageRatio > imageViewRatio {
scale = image.size.height / imageView.bounds.height
} else {
scale = image.size.width / imageView.bounds.width
}
// convert the `rect` into coordinates within the image, itself
let size = rect.size * scale
let origin = CGPoint(x: image.size.width / 2 - (imageView.bounds.midX - rect.minX) * scale,
y: image.size.height / 2 - (imageView.bounds.midY - rect.minY) * scale)
let scaledRect = CGRect(origin: origin, size: size)
// now render the image and grab the appropriate rectangle within
// the image’s coordinate system
let format = UIGraphicsImageRendererFormat()
format.scale = image.scale
format.opaque = false
return UIGraphicsImageRenderer(bounds: scaledRect, format: format).image { _ in
image.draw(at: .zero)
}
}
使用这个扩展:
extension CGSize {
static func * (lhs: CGSize, rhs: CGFloat) -> CGSize {
return CGSize(width: lhs.width * rhs, height: lhs.height * rhs)
}
}
这会产生:
推荐阅读
- hadoop - Docker 中连接字符串的 Hive 连接问题
- css - 为整个页面设置颜色或字体时html和*之间的区别
- python - 我已经为我的飞龙创建了碰撞箱,但碰撞箱要么没有碰撞,要么没有产生输出。我该如何解决?
- r - 在补充行中合并包含 NA 值的两列
- javascript - Dialogflow 聊天机器人与 Dialogflow 的集成
- java - Feign 处理 301 作为异常
- ios - 我的项目中有一个双向链表类型的数据结构,我如何将它存储在 coredata 中?
- php - PHP - 删除 JSON 数组的元素会更改数组语法
- sql - 关于一些 SQL 注入命令的说明
- ruby-on-rails - 使用 React 和 Rails 运行服务器的问题