简体   繁体   English

iOS-从CGBitmapContext获取UIImage

[英]iOS - Get UIImage from CGBitmapContext

I found this code that should draw a text using a UIFont. 我发现此代码应该使用UIFont绘制文本。 I would like to obtain an UIImage from it to make sure it works. 我想从中获取一个UIImage,以确保它可以正常工作。

I obtain an OpenGL texture later for my needs, but since its not showing anything I prefer to verify the code works : 稍后可以根据需要获得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);

Thanks a lot in advance, any help would be appreciated ! 在此先感谢您,任何帮助将不胜感激!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM