How to Add Text to an Image in iOS Swift

How do I add text to an image in iOS Swift?

Ok... I figured it out:

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

}

To call it, you just pass in an image:

textToImage("000", inImage: UIImage(named:"thisImage.png")!, atPoint: CGPointMake(20, 20))

The following links helped me get this straight:

Swift - Drawing text with drawInRect:withAttributes:

How to write text on image in Objective-C (iOS)?

The original goal was to create a dynamic image that I could use in an AnnotaionView such as putting a price at a given location on a map and this worked out great for it. Hope this helps someone trying to do the same thing.

For Swift 3:

 func textToImage(drawText text: NSString, 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 = [
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!
}

For Swift 4:

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

For Swift 5:

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

Adding Text and Images in the same field in Swift

You can use UITextField to add images and text in one field, It can be done by using storyboard also and to do it programmatically is also convenient. Find the below code to add image programmatically in a text field :

var imageView = UIImageView()
var image = UIImage(named: "email.png")
imageView.image = image
emailField.leftView = imageView
emailField.leftViewMode = UITextFieldViewMode.always
emailField.leftViewMode = .always

Add text to a point in image swift

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

How to generate an UIImage from custom text in Swift

You can use this function, you can send any text to this function, inside it i create UILabel and set text attribute as you like

func imageWith(name: String?) -> UIImage? {
let frame = CGRect(x: 0, y: 0, width: 100, height: 100)
let nameLabel = UILabel(frame: frame)
nameLabel.textAlignment = .center
nameLabel.backgroundColor = .lightGray
nameLabel.textColor = .white
nameLabel.font = UIFont.boldSystemFont(ofSize: 40)
nameLabel.text = name
UIGraphicsBeginImageContext(frame.size)
if let currentContext = UIGraphicsGetCurrentContext() {
nameLabel.layer.render(in: currentContext)
let nameImage = UIGraphicsGetImageFromCurrentImageContext()
return nameImage
}
return nil
}

How to Insert Text on Taken Picture by Swift?

I guess you can get the image from photo library first and then pass it to the function which draws text into an Image.

 func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
ImageDisplay.image = textToImage("TextYouWantDraw", inImage: image, atPoint: CGPointMake(10,10))
}

dismissViewControllerAnimated(true, completion: nil)

}

How to add some text under the image using UIKit

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

}



Related Topics



Leave a reply



Submit