I have a saved image in a UIImageView variable.
I'm trying to get the text "Hello" added to this image so that it is all 1 combined image.
I've tried a couple of different things but can't seem to figure it out or get it to work.
Any help would be greatly appreciated:
Here's my code:
//Set the variable that holds the Image to the new image with the text added:
/Attempt #1 function call:
ImageView.image = textToImage(drawText: "Hello", inImage: CameraImageView.image!, atPoint: CGPoint(x: 20, y: 20))
//Attempt #2 function Call:
ImageView.image = generateImageWithText(text: "Hello")
//function #1:
func textToImage(drawText text: String, inImage image: UIImage, atPoint point: CGPoint) -> UIImage {
let textColor = UIColor.white
let textFont = UIFont(name: "Marker Felt", size: 12)!
let scale = image.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()
// added this line to try and get it to work too but it didn't:
ImageView.image = newImage
UIGraphicsEndImageContext()
return newImage!
}
//funtion 2:
func generateImageWithText(text: String) -> UIImage
{
let image = CameraImageView.image
let imageView = UIImageView(image: image)
imageView.backgroundColor = UIColor.clear
imageView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: (image?.size)!)
print("Image size: \(image?.size)")
let label = UILabel(frame: CGRect(origin: CGPoint(x: 20, y: 20), size: CGSize(width: 3024.0, height: 4032.0)/*(width://image?.size)!*/))
label.backgroundColor = UIColor.clear
label.textAlignment = .center
label.textColor = UIColor.white
label.text = text
UIGraphicsBeginImageContextWithOptions(label.bounds.size, false, 0)
imageView.layer.render(in: UIGraphicsGetCurrentContext()!)
label.layer.render(in: UIGraphicsGetCurrentContext()!)
let imageWithText = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return imageWithText!
}
Do you want only to display or do you want to save the combined image ?
For the first, you should
- create a UIView
- in its draw function, draw the image
- then, in draw, draw the text.
You'll have an interesting discussion on various solutions here
https://stackoverflow.com/questions/32006128/how-to-merge-two-uiimages