views:

109

answers:

1

I'm trying to take an NSString and rasterize it as a bitmap (an array of bytes (RGBA))

The closest I've gotten to any information on how to do something like this was in a forum post that suggested something along the lines of


    NSString *myString = [[NSString alloc] initWithString:@"This is a test"];
    NSSize size = {256, 256};
    NSImage *myImage = [[NSImage alloc] initWithSize:size];


    [myImage lockFocus];
    // if you have a second image you're going to overlay on top of the first, do the same except use NSCompositeSourceOver as the operation
    [myString drawAtPoint: NSMakePoint(0, 0)];
    [myImage unlockFocus];

    NSData *tiffData = [myImage TIFFRepresentation];

Unfortunately the app freezes/crashes at [myImage lockFocus].

I've also looked into doing this in CoreGraphics but I'm finding even less information about that. I get bits and pieces, i.e. bitmap contexts and font objects, but nothing that hints at going, 'rasterize this string'

If anyone has got some ideas on how to do this, that would be greatly appreciated

Thanks.

[edit] I just noticed this and this is where I make it obvious that this is new to me. Could I perhaps create a CGContextRef using CGBitmapContextCreate and then 'push' it using UIGraphicsPushContext so that any subsequent drawAtPoint renders to that context ref? Sorry, I'm think out loud now. I should just try it. [edit2] UIGraphicsPushContext is a UIKit method, which unfortunately means iPhone only as far as I'm aware.

A: 

I may as well reply to my own post (one month later)

Basically you have to create a CFString, then use that to create a CTLine. There are methods that can be used to find the dimension of the CTLine which can then be used to create a bitmap context using CGBitmapContextCreate.

From there, the CTLine object can be rendered to the bitmap context using CTLineDraw.

The docs are pretty good for explaining all the other requirements such as position and colour etc, but that's the gist of it for all those who are interested.

Most of the information I used to get me started actually came from this site