首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >iOS -从CGBitmapContext获取UIImage

iOS -从CGBitmapContext获取UIImage
EN

Stack Overflow用户
提问于 2017-08-09 21:32:23
回答 1查看 194关注 0票数 0

我发现这段代码应该可以使用UIFont绘制文本。我想从它获取一个UIImage,以确保它能正常工作。

我后来获得了一个OpenGL纹理来满足我的需要,但是因为它没有显示任何东西,所以我更喜欢验证代码是否工作:

代码语言:javascript
复制
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);

提前感谢,任何帮助都将不胜感激!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-09 22:46:12

找到解决方案:

代码语言:javascript
复制
CGImageRef cgImageFinal = CGBitmapContextCreateImage(context);
UIImage *newImage = [[UIImage alloc]initWithCGImage:cgImageFinal];

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

代码语言:javascript
复制
UIColor *whiteColor = [UIColor whiteColor];
NSDictionary *attrsDictionary = @{
                                  NSFontAttributeName: font,
                                  NSBaselineOffsetAttributeName: @1.0F,
                                  NSParagraphStyleAttributeName: style,
                                  NSForegroundColorAttributeName: whiteColor
                                  };
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45592205

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档