如何在正确的坐标中以快速方式将文本写入图像

时间:2017-03-28 04:53:09

标签: swift image text swift3 xcode8

我正在尝试将文字写入图像但是当我这样做时,文本显示在错误的坐标中,我认为问题是图像在故事板中设置为Aspect Fit,因为它大于屏幕尺寸,这是我的代码:

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

}

2 个答案:

答案 0 :(得分:1)

我想分享解决我问题的代码:

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

答案 1 :(得分:0)

<强>更新

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

    }
    }