Created
February 22, 2016 21:22
-
-
Save voyce/5a8ee4f8b70247c2da5b to your computer and use it in GitHub Desktop.
This file contains 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
func drawText(s: String, w: CGFloat, h: CGFloat, colour:CGColor) -> CGImageRef { | |
let bounds = CGRectMake(0, 0, w, h) | |
// Create the bitmap-backed CoreGraphics contexts | |
let context = CGBitmapContextCreate(nil, Int(w), Int(h), 8, 0, | |
CGColorSpaceCreateDeviceRGB(), | |
CGImageAlphaInfo.PremultipliedFirst.rawValue | CGBitmapInfo.ByteOrder32Little.rawValue) | |
CGContextSetFillColorWithColor(context, colour) | |
CGContextFillRect(context, bounds) | |
// Paragraph styles for the attributed string | |
var alignment = CTTextAlignment.Center | |
var settings = [ | |
CTParagraphStyleSetting(spec: .Alignment, valueSize: sizeofValue(alignment), value: &alignment) | |
] | |
let style = CTParagraphStyleCreate(&settings, 1); | |
// Font for the attributed string | |
let font = UIFont(name: "DIN Condensed", size: h) | |
let attr:CFDictionaryRef = [ | |
NSFontAttributeName:font!, | |
NSForegroundColorAttributeName:UIColor.whiteColor(), | |
NSParagraphStyleAttributeName:style] | |
let attrString = CFAttributedStringCreate(kCFAllocatorDefault, s, attr) | |
let framesetter = CTFramesetterCreateWithAttributedString(attrString) | |
// To align vertically, we need to work out the height of the text | |
let size = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, 0), nil, bounds.size, nil) | |
// We need to translate the path 'downwards' to adjust for the difference between | |
// the bounds height and the text height | |
let top = (bounds.height / 2) - (size.height / 2) - ((font?.descender)! / 2) | |
var transform = CGAffineTransformMakeTranslation(0, -top) | |
let path = CGPathCreateWithRect(bounds, &transform) | |
let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, nil) | |
CTFrameDraw(frame, context!) | |
let cgImage = CGBitmapContextCreateImage(context) | |
return cgImage! | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment