Lester Arévalo
Lester Arévalo

Reputation: 462

how can I write text into a image in swift in the right coordinates

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!
    }

}

Upvotes: 0

Views: 822

Answers (2)

Lester Ar&#233;valo
Lester Ar&#233;valo

Reputation: 462

I would like to share the code that solved my problem:

    import UIKit
    import AVFoundation

    class ExteriorSketchViewController: UIViewController {

        // MARK: - Properties

    var lastPoint = CGPoint.zero

    // MARK: - Outlets

    @IBOutlet weak var template: UIImageView!

    @IBOutlet weak var contentView: UIView! // this is a view inside the main view, contentView has the same size that 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 = drawText(fromPoint: lastPoint, toPoint: lastPoint, text: "X")
        }

    func drawText(fromPoint:CGPoint,toPoint:CGPoint, text: String) -> UIImage {
            let scale = UIScreen.main.scale
            UIGraphicsBeginImageContextWithOptions(self.contentView.frame.size, false, scale)
            let imageRect = CGRect(x: 0, y: 0, width: self.contentView.frame.width, height: self.contentView.frame.height)
            let newRatio = AVMakeRect(aspectRatio: template.image!.size, insideRect: imageRect)
            template.image?.draw(in: newRatio)

            tool.center = toPoint

            let textColor = UIColor.red
            let textFont = UIFont(name: "Helvetica Bold", size: 17)!

            let textFontAttributes = [
                NSFontAttributeName: textFont,
                NSForegroundColorAttributeName: textColor,
                ] as [String : Any]

            let textRect = CGRect(x: fromPoint.x, y: fromPoint.y, width: self.contentView.frame.width, height: self.contentView.frame.height)
            text.draw(in: textRect, withAttributes: textFontAttributes)
            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return newImage
        }
}

Upvotes: 1

tabassum
tabassum

Reputation: 1110

UPdated

ViewController.swift

import UIKit

    class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let imageView = UIImageView(frame: CGRect(x: 50, y: 50, width: 300, height: 300))
        let image =  UIImage(named: "swift")!.addText("swift", atPoint: CGPoint(x: 20, y: 320), textColor:nil, textFont:UIFont.systemFontOfSize(40))
        imageView.image = image

        view.addSubview(imageView)
    }
    }

UIImage.swift

import UIKit

    extension UIImage {

    func addText(drawText: NSString, atPoint: CGPoint, textColor: UIColor?, textFont: UIFont?,size:CGSize) -> UIImage{

        // Setup the font specific variables
        var _textColor: UIColor
        if textColor == nil {
            _textColor = UIColor.whiteColor()
        } else {
            _textColor = textColor!
        }

        var _textFont: UIFont
        if textFont == nil {
            _textFont = UIFont.systemFontOfSize(16)
        } else {
            _textFont = textFont!
        }

        // Setup the image context using the passed image
        let scale = UIScreen.mainScreen().scale
        UIGraphicsBeginImageContextWithOptions(size, false, scale)

        // Setup the font attributes that will be later used to dictate how the text should be drawn
        let textFontAttributes = [
            NSFontAttributeName: _textFont,
            NSForegroundColorAttributeName: _textColor,
            ]

        // Put the image into a rectangle as large as the original image
        drawInRect(CGRectMake(0, 0, size.width, size.height))

        // Create a point within the space that is as bit as the image
        let rect = CGRectMake(atPoint.x, atPoint.y, size.width, size.height)

        // Draw the text into an image
        drawText.drawInRect(rect, withAttributes: textFontAttributes)

        // Create a new image out of the images we have created
        let newImage = UIGraphicsGetImageFromCurrentImageContext()

        // End the context now that we have the image we need
        UIGraphicsEndImageContext()

        //Pass the image back up to the caller
        return newImage

    }
    }

Upvotes: 0

Related Questions