我发现这段代码应该可以使用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);提前感谢,任何帮助都将不胜感激!
发布于 2017-08-09 22:46:12
找到解决方案:
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
};https://stackoverflow.com/questions/45592205
复制相似问题