Chr*_*cke 8 cocoa core-graphics core-text
我需要将居中文本绘制到CGContext.
我开始使用Cocoa方法.我用文本创建了一个NSCell并尝试绘制它:
NSGraphicsContext* newCtx = [NSGraphicsContext
graphicsContextWithGraphicsPort:bitmapContext flipped:true];
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:newCtx];
[pCell setFont:font];
[pCell drawWithFrame:rect inView:nil];
[NSGraphicsContext restoreGraphicsState];
Run Code Online (Sandbox Code Playgroud)
但是CGBitmapContext似乎没有在其上呈现文本.可能是因为我必须为inView:参数传递nil.
所以我尝试将文本渲染切换到Core Graphics:
最简单的方法似乎是使用CGContextSelectFont来使用其postscript名称和点大小来选择字体,但CGContextShowTextAtPoint只接受非unicode字符,并且没有明显的方法将文本拟合到矩形:或计算范围一行文本来手动布局矩形.
然后,有一个可以创建的CGFont,并设置cia CGContextSetFont.绘制此文本需要CGContextShowGlyphsAtPoint,但CGContext似乎缺少计算生成文本的边界矩形或将文本换行到rect的函数.另外,如何将字符串转换为CGGlyphs数组并不明显.
下一个选项是尝试使用CoreText来呈现字符串.但Core Text类非常复杂,虽然有一些示例显示如何以指定的字体,在rect中显示文本,但没有示例演示如何计算CoreText字符串的边界矩形.
所以:
我将继续您的上述方法,但改为使用NSAttributedString.
NSGraphicsContext* newCtx = [NSGraphicsContext graphicsContextWithGraphicsPort:bitmapContext flipped:true];
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:newCtx];
NSAttributedString *string = /* make a string with all of the desired attributes */;
[string drawInRect:locationToDraw];
[NSGraphicsContext restoreGraphicsState];
Run Code Online (Sandbox Code Playgroud)
经过4天的搜索,我终于找到了答案.我真的希望Apple提供更好的文档.所以我们走了
我假设你已经有了CGFontRef.如果不告诉我,我会告诉你如何将资源包中的ttf加载到CgFontRef中.
下面是使用任何CGFontref计算任何字符串边界的代码片段
int charCount = [string length];
CGGlyph glyphs[charCount];
CGRect rects[charCount];
CTFontGetGlyphsForCharacters(theCTFont, (const unichar*)[string cStringUsingEncoding:NSUnicodeStringEncoding], glyphs, charCount);
CTFontGetBoundingRectsForGlyphs(theCTFont, kCTFontDefaultOrientation, glyphs, rects, charCount);
int totalwidth = 0, maxheight = 0;
for (int i=0; i < charCount; i++)
{
totalwidth += rects[i].size.width;
maxheight = maxheight < rects[i].size.height ? rects[i].size.height : maxheight;
}
dim = CGSizeMake(totalwidth, maxheight);
Run Code Online (Sandbox Code Playgroud)
重用相同的函数CTFontGetGlyphsForCharacters来获取字形.要从CGFontRef获取CTFontRef,请使用CTFontCreateWithGraphicsFont()函数
还记得NSFont和CGFontRef是免费桥接的,这意味着它们可以相互融合,无需任何额外工作即可无缝工作.
| 归档时间: |
|
| 查看次数: |
12964 次 |
| 最近记录: |