"Swift. Add text to Image"

Sat 13 September 2014

import UIKit

 

func createARGBBitmapContext(inImage: CGImage) -> CGContext {

    var bitmapByteCount = 0

    var bitmapBytesPerRow = 0

    

    let pixelsWide = CGImageGetWidth(inImage)

    let pixelsHigh = CGImageGetHeight(inImage)

    

    bitmapBytesPerRow = Int(pixelsWide) * 4

    bitmapByteCount = bitmapBytesPerRow * Int(pixelsHigh)

    

    let colorSpace = CGColorSpaceCreateDeviceRGB()

    let bitmapData = malloc(CUnsignedLong(bitmapByteCount))

    let bitmapInfo = CGBitmapInfo.fromRaw(CGImageAlphaInfo.PremultipliedFirst.toRaw())!

    

    let context = CGBitmapContextCreate(bitmapData, pixelsWide, pixelsHigh, CUnsignedLong(8), CUnsignedLong(bitmapBytesPerRow), colorSpace, bitmapInfo)

    

    return context

}

 

func addText(img :UIImage, text :NSString) ->UIImage{

    

    var w = img.size.width;

    var h = img.size.height;

    var colorSpace = CGColorSpaceCreateDeviceRGB();

    

    var context = createARGBBitmapContext(img.CGImage)

    

    CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);

    CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1);

    

    

    var path = CGPathCreateMutable(); //1

    CGPathAddRect(path, nil, CGRectMake(w - 90, 1, 100, 20));

    

    var attString = NSAttributedString(string: text) //2

    

    var framesetter = CTFramesetterCreateWithAttributedString(attString); //3

    var frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, attString.length), path, nil);

    

    CTFrameDraw(frame, context); //4

    

    var imageMasked:CGImage = CGBitmapContextCreateImage(context) as CGImage

    

    return UIImage(CGImage: imageMasked);

}

 

var img = UIImage(named: "collection.png")

 

var res = addText(img, "Text To Add")