绘图文本与核心图形 [英] Drawing Text with Core Graphics

查看:128
本文介绍了绘图文本与核心图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将中心文本绘制到CGContext。

I need to draw centered text to a CGContext.

我开始使用Cocoa方法。我创建了一个NSCell的文本,并试图绘制它:

I started with a Cocoa approach. I created a NSCell with the text and tried to draw it thus:

NSGraphicsContext* newCtx = [NSGraphicsContext
     graphicsContextWithGraphicsPort:bitmapContext flipped:true];
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:newCtx];
[pCell setFont:font];
[pCell drawWithFrame:rect inView:nil];
[NSGraphicsContext restoreGraphicsState];

但是CGBitmapContext似乎没有呈现文本。可能是因为我必须为inView:参数传递nil。

But the CGBitmapContext doesn't seem to have the text rendered on it. Possibly because I have to pass nil for the inView: parameter.

所以我尝试将文本渲染切换到Core Graphics:

So I tried switching text rendering to Core Graphics:

最简单的方法似乎是使用CGContextSelectFont选择使用其后缀名称和点大小的字体,但CGContextShowTextAtPoint只接受非Unicode字符,没有明显的方式来适应文本到矩形:或计算一行文本的范围以手动布局矩形。

The simplest way seems to be to use CGContextSelectFont to select a font using its postscript name, and point size, but CGContextShowTextAtPoint only takes non-unicode characters, and there is no apparent way to fit the text to a rectangle: or to compute the extents of a line of text to manually lay out the rectangle.

然后,有一个CGFont可以创建,并设置cia CGContextSetFont。绘制这个文本需要CGContextShowGlyphsAtPoint,但是CGContext似乎缺少计算生成的文本的边界矩形的功能,或者将文本包裹到一个矩形。另外,如何将字符串转换为CGGlyph数组并不明显。

Then, there is a CGFont that can be created, and set cia CGContextSetFont. Drawing this text requires CGContextShowGlyphsAtPoint, but again the CGContext seems to be lacking functions to compute the bounding rect of generated text, or to wrap the text to a rect. Plus how to transform a string to an array of CGGlyphs is not obvious.

下一个选项是尝试使用CoreText来渲染字符串。但是Core Text类非常复杂,虽然有一些示例演示了如何在一个指定的字体中显示文本,但是没有示例演示如何计算CoreText字符串的边界矩形。

The next option is to try using CoreText to render the string. But the Core Text classes are hugely complicated, and while there are samples that show how to display text, in a specified font, in a rect, there are no samples demonstrating how to compute the bounding rect of a CoreText string.

所以:


  • 给定一个CGFont的CGContext如何计算一些文本的边界,以及如何将文本字符串转换为CGGlyphs数组?

  • 给定一个字符串,一个CGContext和一个postscript名称和点大小,我需要创建什么Core Text对象

  • 给定一个字符串和一个NSFont - 如何将该字符串转换为一个CGBitmapContext?

推荐答案

我会继续使用上述方法,使用NSAttributedString。

I would continue with your above approach but use NSAttributedString instead.

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];

这篇关于绘图文本与核心图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆