Shin622
Shin622

Reputation: 645

Add text to a point in image swift

I am using UITapGestureRecognizer to get coordinates in a UIImageView, then use that coordinates as a position where to add text to image. The problem the text was not added exactly to where I touched on UIImageView Could you help me to solve problem or give me some suggest

    @IBOutlet var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        imageView.image = UIImage(named: documentsPath + "/bach.jpg")
        let imageViewTapped = UITapGestureRecognizer(target: self, action: #selector(self.tapAction(_:)))
        imageViewTapped.numberOfTouchesRequired = 1
        imageViewTapped.delegate = self
        imageView.addGestureRecognizer(imageViewTapped)
    }

    func tapAction(_ sender: UITapGestureRecognizer) {
        let point = sender.location(in: self.imageView)
        print("x \(point.x) y \(point.y) ")
        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let image = UIImage(named: documentsPath + "/bach.jpg")!
        let newImage = textToImage(drawText: "㊗️Hello", inImage: image, atPoint: CGPoint(x: point.x, y: point.y))
        imageView.image = newImage
    }

    // Add text to image
    func textToImage(drawText text: NSString, inImage image: UIImage, atPoint point: CGPoint) -> UIImage {
        let textColor = UIColor.white
        let textFont = UIFont(name: "Helvetica Bold", size: 300)!
        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))
        text.draw(at: point, withAttributes: textFontAttributes)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage!
    }

Upvotes: 0

Views: 1902

Answers (3)

Krishnarjun Banoth
Krishnarjun Banoth

Reputation: 1570

Replace your saveImage method with the following code snippet.

func saveImage()
{
  UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, UIScreen.main.scale)
  imageView.layer.render(in: UIGraphicsGetCurrentContext()!)
  let image = UIGraphicsGetImageFromCurrentImageContext()
  UIGraphicsEndImageContext()

  if let data = UIImagePNGRepresentation(image!) {
        let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
        try? data.write(to: filename)
    }
}

Upvotes: 1

Krishnarjun Banoth
Krishnarjun Banoth

Reputation: 1570

Code to save image in document directly in png format. If you want to save it in jpeg formate then just change that UIImagePNGRepresentation line into UIImageJPEGRepresentation(image, 0.9).

func saveImage()
{
    if let image = UIImage(named: "test.png") {
        if let data = UIImagePNGRepresentation(image) {
            let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
            try? data.write(to: filename)
        }
    }
}

func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

Upvotes: 1

Krishnarjun Banoth
Krishnarjun Banoth

Reputation: 1570

class ViewController1: UIViewController {
let lblNew = UILabel()
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
    super.viewDidLoad()
    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    imageView.image = UIImage(named: documentsPath + "/bach.jpg")
    imageView.isUserInteractionEnabled = true
    let imageViewTapped = UITapGestureRecognizer(target: self, action: #selector(self.tapAction(_:)))
    imageViewTapped.numberOfTouchesRequired = 1
    imageViewTapped.delegate = self as? UIGestureRecognizerDelegate
    imageView.addGestureRecognizer(imageViewTapped)
}

func tapAction(_ sender: UITapGestureRecognizer) {
    let point = sender.location(in: self.imageView)
    print("x \(point.x) y \(point.y) ")
    textToImage(drawText: "㊗️Hello", atPoint: CGPoint(x: point.x, y: point.y))

}

// Add text to image
func textToImage(drawText text: NSString, atPoint point: CGPoint) {

    lblNew.frame = CGRect(x: point.x, y: point.y, width: 200.0, height: 10)
    lblNew.textAlignment = .left
    lblNew.text = text as String
    lblNew.textColor = UIColor.white
    imageView.addSubview(lblNew)
}
}

Upvotes: 2

Related Questions