Swift在图像上绘制图像资源

时间:2018-06-07 01:54:16

标签: ios swift uigraphicscontext

我正在尝试将一个名为GreyCircle(小灰色圆圈,25x25)的图像资源绘制到Swift 4中的图像上,但我似乎无法做到正确。顺便说一句,这是一个点击手势功能,也就是说,我正在尝试绘制用户点击照片的灰色圆圈。 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行不正确,但这是我最近的尝试。我确定我错过了一些头脑发热的东西。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:-1)

我认为首先你需要在imageView中添加greyCircle并在主视图上添加imageview。然后在获取主视图的当前上下文之后......这可能会对你有所帮助