简体   繁体   English

使用swift在图像上叠加文本

[英]overlaying text on image using swift

I am trying to overlay some text on an image using Swift and am looking at this code here: (src: How do I add text to an image in iOS Swift ) 我试图使用Swift在图像上叠加一些文本,我在这里查看此代码:(src: 如何在iOS Swift中向图像添加文本

This places the text right in the center. 这会将文本放在中心位置。 I have been changing the values in 我一直在改变价值观

 var rect = CGRectMake(10,150, inImage.size.width,    
   inImage.size.height)

but I am unable to get the text to show in the lower left corner. 但是我无法在左下角显示文字。 Can someone help and show what I am missing here ? 有人可以帮助并展示我在这里缺少的东西吗?

I am adding the modified image using this line: 我正在使用以下行添加修改后的图像:

modImage = self.textToImage("000", inImage: UIImage(named:"thisImage.png")!, atPoint: CGPointMake(10, 400))

Below is the function... 以下是功能......

func textToImage(drawText: NSString, inImage: UIImage, atPoint: CGPoint) -> UIImage{

    // Setup the font specific variables
    var textColor = UIColor.whiteColor()
    var textFont = UIFont(name: "Helvetica Bold", size: 12)!

    // Setup the image context using the passed image
    let scale = UIScreen.mainScreen().scale
    UIGraphicsBeginImageContextWithOptions(inImage.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
    inImage.drawInRect(CGRectMake(0, 0, inImage.size.width, inImage.size.height))

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

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

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

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

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

}

Details 细节

xCode 9.1, Swift 4 xCode 9.1,Swift 4

Solution

extension UIView 扩展UIView

extension UIView {

    func copyObject<T: UIView> () -> T? {
        let archivedData = NSKeyedArchiver.archivedData(withRootObject: self)
        return NSKeyedUnarchiver.unarchiveObject(with: archivedData) as? T
    }
}

extension UIImage 扩展UIImage

 extension UIImage {

    typealias EditSubviewClosure<T: UIView> = (_ parentSize: CGSize, _ viewToAdd: T)->()

    func with<T: UIView>(view: T, editSubviewClosure: EditSubviewClosure<T>) -> UIImage {

        if let copiedView = view.copyObject() as? T {
            UIGraphicsBeginImageContext(size)

            let basicSize = CGRect(origin: .zero, size: size)
            draw(in: basicSize)
            editSubviewClosure(size, copiedView)
            copiedView.draw(basicSize)

            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return newImage!
        }
        return self

    }
}

extension UIImageView 扩展UIImageView

 extension UIImageView {

    enum ImageAddingMode {
        case changeOriginalImage
        case addSubview
        case addCopiedSubview
    }

    func drawOnCurrentImage<T: UIView>(view: T, mode: ImageAddingMode, editSubviewClosure: @escaping UIImage.EditSubviewClosure<T>) {

        guard let image = image else {
            return
        }

        let addSubView: (T) -> () = { view in
            editSubviewClosure(self.frame.size, view)
            self.addSubview(view)
        }

        switch mode {
            case .changeOriginalImage:
                self.image = image.with(view: view, editSubviewClosure: editSubviewClosure)

            case .addSubview:
                addSubView(view)

            case .addCopiedSubview:
                if let copiedView = view.copyObject() as? T {
                    addSubView(copiedView)
                }
        }
    }
}

Usage 用法

Sample 1 样品1

func sample1(label: UILabel) {
    imageView.contentMode = .scaleAspectFit
    imageView.image = UIImage(named: "wall")?.with(view: label) { (parentSize, viewToAdd) in
        print("parentSize: \(parentSize)")
        viewToAdd.font = UIFont.systemFont(ofSize: 40)
        viewToAdd.textColor = .yellow
        viewToAdd.bounds = CGRect(x: 40, y: 40, width: 200, height: 40)
    }
}

在此输入图像描述

Sample 2 样本2

func sample2(label: UILabel) {
    imageView.image = UIImage(named: "wall")
    imageView.contentMode = .scaleAspectFit
    imageView.drawOnCurrentImage(view: label, mode: .changeOriginalImage) { (parentSize, viewToAdd) in
        print("parentSize: \(parentSize)")
        viewToAdd.font = UIFont.systemFont(ofSize: 40)
        viewToAdd.textColor = .yellow
        viewToAdd.textAlignment = .right
        let width: CGFloat = 200
        let height: CGFloat = 30
        let indent: CGFloat = 40
        viewToAdd.bounds = CGRect(x: parentSize.width - width - indent, y: parentSize.height - height - indent, width: width, height: height)
    }
}

在此输入图像描述

Sample 3 样本3

func sample3(label: UILabel) {
    imageView.image = UIImage(named: "wall")
    imageView.contentMode = .scaleAspectFill
    imageView.drawOnCurrentImage(view: label, mode: .addSubview) { (parentSize, viewToAdd) in
        print("parentSize: \(parentSize)")
        viewToAdd.font = UIFont.systemFont(ofSize: 16)
        viewToAdd.textColor = .yellow
        viewToAdd.frame = CGRect(x: 40, y: 40, width: 200, height: 20)
    }
}

在此输入图像描述

Sample 4 样本4

func sample4(label: UILabel) {
    imageView.image = UIImage(named: "wall")
    imageView.contentMode = .scaleAspectFill
    imageView.drawOnCurrentImage(view: label, mode: .addCopiedSubview) { (parentSize, viewToAdd) in
        print("parentSize: \(parentSize)")
        viewToAdd.font = UIFont.systemFont(ofSize: 16)
        viewToAdd.textColor = .yellow
        viewToAdd.frame = CGRect(x: 40, y: 40, width: 200, height: 20)
    }
}

在此输入图像描述

Full sample 完整样本

Do not forget to add the solution code here 不要忘记在此处添加解决方案代码

import UIKit

class ViewController: UIViewController {

    let imageView = UIImageView(frame: CGRect(x: 50, y: 50, width: 300, height: 300))

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let label = UILabel(frame: CGRect(x: 20, y: 20, width: 80, height: 30))
        label.text = "Blablabla"
        label.font = UIFont.systemFont(ofSize: 20)
        label.textColor = .black
        view.addSubview(label)

        sample1(label: label)
        //sample2(label: label)
        //sample3(label: label)
        //sample4(label: label)

        imageView.clipsToBounds = true
        view.addSubview(imageView)
    }

    func sample1(label: UILabel) {
        imageView.contentMode = .scaleAspectFit
        imageView.image = UIImage(named: "wall")?.with(view: label) { (parentSize, viewToAdd) in
            print("parentSize: \(parentSize)")
            viewToAdd.font = UIFont.systemFont(ofSize: 40)
            viewToAdd.textColor = .yellow
            viewToAdd.bounds = CGRect(x: 40, y: 40, width: 200, height: 20)
        }
    }

    func sample2(label: UILabel) {
        imageView.image = UIImage(named: "wall")
        imageView.contentMode = .scaleAspectFit
        imageView.drawOnCurrentImage(view: label, mode: .changeOriginalImage) { (parentSize, viewToAdd) in
            print("parentSize: \(parentSize)")
            viewToAdd.font = UIFont.systemFont(ofSize: 40)
            viewToAdd.textColor = .yellow
            viewToAdd.textAlignment = .right
            let width: CGFloat = 200
            let height: CGFloat = 30
            let indent: CGFloat = 40
            viewToAdd.bounds = CGRect(x: parentSize.width - width - indent, y: parentSize.height - height - indent, width: width, height: height)
        }
    }

    func sample3(label: UILabel) {
        imageView.image = UIImage(named: "wall")
        imageView.contentMode = .scaleAspectFill
        imageView.drawOnCurrentImage(view: label, mode: .addSubview) { (parentSize, viewToAdd) in
            print("parentSize: \(parentSize)")
            viewToAdd.font = UIFont.systemFont(ofSize: 16)
            viewToAdd.textColor = .yellow
            viewToAdd.frame = CGRect(x: 40, y: 40, width: 200, height: 20)
        }
    }

    func sample4(label: UILabel) {
        imageView.image = UIImage(named: "wall")
        imageView.contentMode = .scaleAspectFill
        imageView.drawOnCurrentImage(view: label, mode: .addCopiedSubview) { (parentSize, viewToAdd) in
            print("parentSize: \(parentSize)")
            viewToAdd.font = UIFont.systemFont(ofSize: 16)
            viewToAdd.textColor = .yellow
            viewToAdd.frame = CGRect(x: 40, y: 40, width: 200, height: 20)
        }
    }
}

Great answer Vasily! 伟大的回答瓦西里!

but in my situation I needed to add these fixes. 但在我的情况下,我需要添加这些修复程序。

TEXT IS VERY SMALL 文字非常小

I ran a situation where the text was super small, maybe because the UIImage size was too small for the selected font of 14, so I fixed this by giving a huge font of 120. 我遇到了一个文本非常小的情况,可能是因为UIImage的大小对于14的所选字体而言太小了,所以我通过给出一个120的巨大字体来修复它。

TEXT IS NOT DISPLAYED AT THE GIVEN CGPOINT 文字没有在GIVEN CGPOINT上显示

In the same context of a big UIImage size, the position given to the extension was misplacing the text, the fix: added these 2 lets with the ratio of height and width computed and then multiplied for x,y points. 在大UIImage大小的相同上下文中,赋予扩展名的位置错误地放置了文本,修复:添加这些2让我们计算高度和宽度的比率,然后乘以x,y点。

let widthRatio = size.width/UIScreen.main.bounds.width
let heightRatio = size.height/UIScreen.main.bounds.height

Hope that helps anybody! 希望能帮助任何人!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM