I wanted to display the characters on the image, but the URL was very reliable β https://qiita.com/taku/items/2c246d92bec494a1df5e
I copied the above URL as it is, but since I am a Swift beginner, I made a note of it because it took a lot of time with a little change due to the Swift version upgrade. .. With this source, I was able to display the text on the image even with Swift 12.
//Display text on top of the image
func drawText(image :UIImage) ->UIImage
{
let text = "Sample Text"
let tmpImage = UIImage(named: "1")
let font = UIFont.boldSystemFont(ofSize: 32)
let imageRect = CGRect(x: 0, y: 0, width: tmpImage.size.width, height: tmpImage.size.height)
UIGraphicsBeginImageContext(tmpImage.size);
tmpImage.draw(in: imageRect)
let textRect = CGRect(x: 5, y: 5, width: tmpImage.size.width - 5 , height: tmpImage.size.height - 5)
let textStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
let textFontAttributes = [
NSAttributedString.Key.font: font,
NSAttributedString.Key.foregroundColor: UIColor.black,
NSAttributedString.Key.paragraphStyle: textStyle
] as [NSAttributedString.Key : Any]
text.draw(in: textRect, withAttributes: textFontAttributes)
let newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext()
return newImage!
}
I really want to dynamically place text in an Image retrieved from JSON via Alamofire, but that's about to happen ...
Recommended Posts