首页 > 解决方案 > 在图像上快速绘制图像资产

问题描述

我正在尝试在 Swift 4 中将名为 GreyCircle(小灰色圆圈,25x25)的图像资产绘制到图像上,但我似乎无法正确处理。顺便说一句,这是在一个点击手势功能中,也就是说,我正在尝试绘制用户点击照片的灰色圆圈。displayedImage保存当前正在显示的图像。

代码:

self.touchPoint = gestureRecognizer.location(in: self.view)
let greyCircle = UIImage(named: "GreyCircle")   

UIGraphicsBeginImageContextWithOptions(displayedImage.size, false, 0.0)
displayedImage.draw(in: CGRect(x:0, y:0, width:displayedImage.size.width, height: displayedImage.size.height))
greyCircle.draw(in: CGRect(x:touchPoint.x, y:touchPoint.y, width:displayedImage.size.width, height: displayedImage.size.height))
let newImag = UIGraphicsGetImageFromCurrentImageContext()

UIGraphicsEndImageContext()
displayedImage = newImag

greyCircle.draw行不正确,但这是我的最新尝试。我确定我错过了一些愚蠢的东西。

标签: iosswiftuigraphicscontext

解决方案


您想将触摸点转换为图像视图的边界。然后在绘制圆圈时,使用圆圈的大小,而不是图像的大小。

let touchPoint = gestureRecognizer.location(in: displayedImage)
let greyCircle = UIImage(named: "GreyCircle")   

UIGraphicsBeginImageContextWithOptions(displayedImage.size, false, 0.0)
displayedImage.draw(in: CGRect(x:0, y:0, width:displayedImage.size.width, height: displayedImage.size.height))
greyCircle.draw(in: CGRect(x:touchPoint.x, y:touchPoint.y, width: greyCircle.size.width, height: greyCircle.size.height))
let newImag = UIGraphicsGetImageFromCurrentImageContext()

UIGraphicsEndImageContext()
displayedImage = newImag

推荐阅读