Xys
Xys

Reputation: 10819

iOS - Get UIImage from CGBitmapContext

I found this code that should draw a text using a UIFont. I would like to obtain an UIImage from it to make sure it works.

I obtain an OpenGL texture later for my needs, but since its not showing anything I prefer to verify the code works :

NSUInteger width, height, i;
CGContextRef context;
void *data;
CGColorSpaceRef colorSpace;
UIFont *font;

font = [UIFont fontWithName:name size:size];

width = (NSUInteger)dimensions.width;
if ((width != 1) && (width & (width - 1))) {
    i = 1;
    while (i < width)
        i *= 2;
    width = i;
}
height = (NSUInteger)dimensions.height;
if ((height != 1) && (height & (height - 1))) {
    i = 1;
    while (i < height)
        i *= 2;
    height = i;
}

colorSpace = CGColorSpaceCreateDeviceGray();
data = calloc(height, width);
context = CGBitmapContextCreate(data, width, height, 8, width, colorSpace, kCGImageAlphaNone);

CGColorSpaceRelease(colorSpace);

CGContextSetGrayFillColor(context, 1.0, 1.0);
CGContextTranslateCTM(context, 0.0, height);
CGContextScaleCTM(context, 1.0f, -1.0f); //NOTE: NSString draws in UIKit referential i.e. renders upside-down compared to CGBitmapContext referential
UIGraphicsPushContext(context);

NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setLineBreakMode:NSLineBreakByWordWrapping];

NSDictionary *attrsDictionary = @{
                                  NSFontAttributeName: font,
                                  NSBaselineOffsetAttributeName: @1.0F,
                                  NSParagraphStyleAttributeName: style
                                  };

[string drawInRect:CGRectMake(0, 0, dimensions.width, dimensions.height)
    withAttributes:attrsDictionary];

UIGraphicsPopContext();

// Here I use "void *data" to obtain an OpenGL texture
// ...
// ...

CGContextRelease(context);
free(data);

Thanks a lot in advance, any help would be appreciated !

Upvotes: 0

Views: 282

Answers (1)

Xys
Xys

Reputation: 10819

Found the solution :

CGImageRef cgImageFinal = CGBitmapContextCreateImage(context);
UIImage *newImage = [[UIImage alloc]initWithCGImage:cgImageFinal];

Also, I needed to set the color of the text to white :

UIColor *whiteColor = [UIColor whiteColor];
NSDictionary *attrsDictionary = @{
                                  NSFontAttributeName: font,
                                  NSBaselineOffsetAttributeName: @1.0F,
                                  NSParagraphStyleAttributeName: style,
                                  NSForegroundColorAttributeName: whiteColor
                                  };

Upvotes: 1

Related Questions