Skip to content

Instantly share code, notes, and snippets.

@aataraxiaa
Created November 17, 2015 20:41
Show Gist options
  • Save aataraxiaa/14885c5e2c8a5ccfbddb to your computer and use it in GitHub Desktop.
Save aataraxiaa/14885c5e2c8a5ccfbddb to your computer and use it in GitHub Desktop.
Swift function for adding text to a UIImage
func addTextToImage(text: NSString, inImage: UIImage, atPoint:CGPoint) -> UIImage{
// Setup the font specific variables
let textColor = YOUR_COLOR
let textFont = YOUR_FONT
//Setups up the font attributes that will be later used to dictate how the text should be drawn
let textFontAttributes = [
NSFontAttributeName: textFont,
NSForegroundColorAttributeName: textColor,
]
// Create bitmap based graphics context
UIGraphicsBeginImageContextWithOptions(inImage.size, false, 0.0)
//Put the image into a rectangle as large as the original image.
inImage.drawInRect(CGRectMake(0, 0, inImage.size.width, inImage.size.height))
// Our drawing bounds
let drawingBounds = CGRectMake(0.0, 0.0, inImage.size.width, inImage.size.height)
let textSize = text.sizeWithAttributes([NSFontAttributeName:textFont])
let textRect = CGRectMake(drawingBounds.size.width/2 - textSize.width/2, drawingBounds.size.height/2 - textSize.height/2,
textSize.width, textSize.height)
text.drawInRect(textRect, withAttributes: textFontAttributes)
// Get the image from the graphics context
let newImag = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImag
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment