iOS - 从 CGBitmapContext 获取 UIImage

iOS - Get UIImage from CGBitmapContext

我发现这段代码应该使用 UIFont 绘制文本。我想从中获取一个 UIImage 以确保它有效。

我稍后会根据需要获取 OpenGL 纹理,但由于它没有显示任何内容,我更愿意验证代码是否有效:

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);

在此先致谢,如有任何帮助,我们将不胜感激!

找到解决方案:

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

此外,我需要将文本的颜色设置为白色:

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