【发布时间】:2017-08-09 13:32:23
【问题描述】:
我发现这段代码应该使用 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);
非常感谢,任何帮助将不胜感激!
【问题讨论】: