Search code examples
iosswiftuikituiimagecore-graphics

How to add some text under the image using UIKit


I have an image like this:

first

But I want to add some text under this image and get it like a new UIImage, for example:

second

As I understand I should create a new image. Then put my image into it and add a text. How can I do it?

I tried to use something like this, but couldn't place my text under the image

func textToImage(drawText text: String, inImage image: UIImage, atPoint point: CGPoint) -> UIImage {
    let textColor = UIColor.white
    let textFont = UIFont(name: "Helvetica Bold", size: 12)!

    let scale = UIScreen.main.scale
    UIGraphicsBeginImageContextWithOptions(image.size, false, scale)

    let textFontAttributes = [
        NSAttributedStringKey.font: textFont,
        NSAttributedStringKey.foregroundColor: textColor,
        ] as [NSAttributedStringKey : 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!
}

PS Background of my image is clear. Red is a background of another view.


Solution

  • In general you should always show some code of what you have attempted so far. But this is a kind of trivial view that should looks something similar to:

    class ViewWithImage: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        fatalError("storyboards no thanks")
    }
    
    private func setup() {
        backgroundColor = .red
        let imageView = UIImageView()
        imageView.image = UIImage(named: "garbagecan")
        imageView.contentMode = .scaleAspectFit
        imageView.tintColor = .white
        
        let deleteLabel = UILabel()
        deleteLabel.text = "Delete"
        deleteLabel.textColor = .white
        
        let vStack = UIStackView()
        vStack.axis = .vertical
        vStack.spacing = 8
        addSubview(vStack)
        
        NSLayoutConstraint.activate([
            vStack.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 16),
            vStack.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -16),
            vStack.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -16),
            vStack.topAnchor.constraint(equalTo: self.topAnchor, constant: 16)
        ])
        
        vStack.addArrangedSubview(imageView)
        vStack.addArrangedSubview(deleteLabel)
    }
    

    }