Skip to content

Instantly share code, notes, and snippets.

@bricklife
Last active July 17, 2017 10:40
Show Gist options
  • Save bricklife/10a5407ffaf722b3c143cd89c0fba683 to your computer and use it in GitHub Desktop.
Save bricklife/10a5407ffaf722b3c143cd89c0fba683 to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import UIKit
func createImage(text: String, fontSize: CGFloat, imageSize: CGSize) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(imageSize, false, 0)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
let rect = CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height)
// Fill background
context.setFillColor(UIColor.white.cgColor)
context.fill(rect)
// Draw text
let textStyle = NSMutableParagraphStyle()
textStyle.alignment = .center
let textFontAttributes = [
NSFontAttributeName: UIFont.systemFont(ofSize: fontSize),
NSForegroundColorAttributeName: UIColor.black,
NSParagraphStyleAttributeName: textStyle
]
let textRect = CGRect(x: 0, y: (rect.height - fontSize) / 2, width: rect.width, height: fontSize)
text.draw(in: textRect, withAttributes: textFontAttributes)
// Create image
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
let image = createImage(text: NSDate().description, fontSize: 32, imageSize: CGSize(width: 512, height: 512))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment