Yorma
Yorma

Reputation: 80

Swift draw image asset on an image

I'm trying to draw an image asset called GreyCircle (small grey circle, 25x25) onto an image in Swift 4, but I can't seem to get it right. By the way, this is in a tap-gesture function, that is, I'm trying to draw the grey circle where the user taps on a photo. displayedImage holds the current image being displayed.

Code:

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

The greyCircle.draw line is not correct, but it's my latest attempt. I'm sure I'm missing something bone-headed.

Upvotes: 1

Views: 1451

Answers (1)

rmaddy
rmaddy

Reputation: 318774

You want to translate the touch point to the bounds of the image view. Then when drawing the circle, use the circle's size, not the image's size.

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

Upvotes: 1

Related Questions