将文本绘制到CGBitmapContext中

问题描述 投票:0回答:1

我有一个应用程序,在UIView呈现CGContextdrawRect。我还使用背景渲染器导出这些渲染。它使用相同的渲染逻辑(比实时更快)渲染到CGBitmapContext(我随后将其转换为mp4文件)。

我注意到输出视频有许多奇怪的故障。例如旋转的图像,渲染图像的奇怪重复,随机噪声和定时也是奇数。

我正在寻找调试方法。对于计时问题,我想我会渲染一个字符串,告诉我我正在查看哪个帧,只是发现CGContext中的渲染文本没有很好地记录。实际上,围绕大部分核心图形的文档对我的一些经验来说是非常不可原谅的。

具体来说,我想知道如何将文本呈现到上下文中。如果它的核心文本,它必须与核心图形上下文互操作吗?总的来说,我很欣赏有关进行位图渲染和调试结果的任何提示和建议。

core-graphics
1个回答
0
投票

另一个问题:How to convert Text to Image in Cocoa Objective-C

我们可以使用CTLineDraw在CGBitmapContext示例代码中绘制文本:

NSString* string = @"terry.wang";
CGFloat fontSize = 10.0f;
// Create an attributed string with string and font information
CTFontRef font = CTFontCreateWithName(CFSTR("Helvetica Light"), fontSize, nil);
NSDictionary* attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                            (id)font, kCTFontAttributeName, 
                            nil];
NSAttributedString* as = [[NSAttributedString alloc] initWithString:string attributes:attributes];
CFRelease(font);

// Figure out how big an image we need 
CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef)as);
CGFloat ascent, descent, leading;
double fWidth = CTLineGetTypographicBounds(line, &ascent, &descent, &leading);

// On iOS 4.0 and Mac OS X v10.6 you can pass null for data 
size_t width = (size_t)ceilf(fWidth);
size_t height = (size_t)ceilf(ascent + descent);
void* data = malloc(width*height*4);

// Create the context and fill it with white background
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast;
CGContextRef ctx = CGBitmapContextCreate(data, width, height, 8, width*4, space, bitmapInfo);
CGColorSpaceRelease(space);
CGContextSetRGBFillColor(ctx, 1.0, 1.0, 1.0, 1.0); // white background
CGContextFillRect(ctx, CGRectMake(0.0, 0.0, width, height));

// Draw the text 
CGFloat x = 0.0;
CGFloat y = descent;
CGContextSetTextPosition(ctx, x, y);
CTLineDraw(line, ctx);
CFRelease(line);
© www.soinside.com 2019 - 2024. All rights reserved.