I am trying to write text into an image but when I do it the text show in the wrong coordinates, I think that the problem is that the image is set as Aspect Fit in the storyboard because is bigger than the screen size, this is my code:
class ExteriorSketchViewController: UIViewController {
// MARK: - Properties
var lastPoint = CGPoint.zero
// MARK: - Outlets
@IBOutlet weak var template: UIImageView!
// MARK: - Lifecycle methods
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
lastPoint = touch.location(in: self.view)
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let currentPoint = touch.location(in: self.view)
lastPoint = currentPoint
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
template.image = textToImage(drawText: "x", inImage: template.image!, atPoint: lastPoint)
}
func textToImage(drawText text: NSString, inImage image: UIImage, atPoint point: CGPoint) -> UIImage {
let textColor = UIColor.red
let textFont = UIFont(name: "Helvetica Bold", size: 32)!
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(image.size, false, scale)
let textFontAttributes = [
NSFontAttributeName: textFont,
NSForegroundColorAttributeName: textColor,
] as [String : Any]
image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
let rect = CGRect(origin: point, size: image.size)
text.draw(in: rect, withAttributes: textFontAttributes)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}