Created
April 2, 2016 12:45
-
-
Save MathieuWhite/8c28ae671fa9714ddd9e595e54ce5905 to your computer and use it in GitHub Desktop.
UIImage Extension that creates an image with text
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// UIImageExtension.swift | |
// | |
// Created by Mathieu White on 2016-02-05. | |
// Copyright © 2016 Mathieu White. All rights reserved. | |
// | |
import UIKit | |
extension UIImage | |
{ | |
/** | |
This method creates a UIView the with the text, color and size passed in, | |
and returns it as a UIImage. | |
- parameter text: the text to display in the center of the image | |
- parameter color: the text color of the image | |
- parameter backgroundColor: the background color of the image | |
- parameter size: the size of the image | |
- returns: a UIImage with the parameters specified | |
*/ | |
class func imageWithText(text: String, color: UIColor, backgroundColor: UIColor, size: CGSize) -> UIImage? | |
{ | |
// Begin the image context | |
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.mainScreen().scale) | |
// Get the context, and generate the image | |
if let context = UIGraphicsGetCurrentContext() | |
{ | |
// Initialize the image view | |
let imageView: UIView = UIView(frame: CGRect(origin: CGPointZero, size: size)) | |
imageView.backgroundColor = backgroundColor | |
// Initialize the label | |
let textLabel: UILabel = UILabel(frame: imageView.frame) | |
textLabel.text = text | |
textLabel.textColor = color | |
textLabel.textAlignment = NSTextAlignment.Center | |
textLabel.font = UIFont.fontOfSize((size.height < size.width) ? size.height * 0.36 : size.width * 0.36, | |
weight: UIFont.FontWeight.Light) | |
textLabel.adjustsFontSizeToFitWidth = true | |
textLabel.center = imageView.center | |
// Add the label to the imageView | |
imageView.addSubview(textLabel) | |
// Render the image view | |
imageView.layer.renderInContext(context) | |
// Get the image | |
let image = UIGraphicsGetImageFromCurrentImageContext() | |
// End the image context | |
UIGraphicsEndImageContext() | |
// Return the image | |
return image | |
} | |
// End the image context | |
UIGraphicsEndImageContext() | |
// Something went wrong | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment