iOS:如何使用 Quartz 测量字符串的宽度和高度?

标签 ios objective-c quartz-graphics core-text

在我问问题之前,这是来自 Apple 的文档:如何使用 Quartz 确定字符串的宽度:

If text measurements are important to your application, it is possible to calculate them using Quartz 2D functions. However, you might first consider using ATSUI, whose strength is in text layout and measurement. ATSUI has several functions that obtain text metrics. Not only can you obtain after-layout text metrics, but in the rare cases you need them, you can obtain before-layout text metrics. Unlike Quartz, for which you must perform the calculations yourself, ATSUI computes the measurements for you. For example, you can obtain the image bounding rectangle for text by calling the ATSUI function ATSUMeasureTextImage.

If you decide that Quartz text suits your needs better than ATSUI (or Cocoa), you can follow these steps to measure the width of text before Quartz draws it:

  1. Call the function CGContextGetTextPosition to obtain the current text position.
  2. Set the text drawing mode to kCGTextInvisible using the function CGContextSetTextDrawingMode.
  3. Draw the text by calling the function CGContextShowText to draw the text at the current text position.
  4. Determine the final text position by calling the function CGContextGetTextPosition.
  5. Subtract the starting position from the ending position to determine the width of the text.

这是我的问题:

  1. 这真的是使用 Core Graphics 确定字符串宽度的最佳方法吗?它看起来很脆弱,并且由于我的文本与 2D 图形元素共存,所以我想对所有渲染使用相同的上下文。我希望有一些紧凑的方法,比如:

    CGContextGetTextWidthAndHeight(context, text);
    
  2. 我读到 ATSUI 已过时,将被 Core Text 取代。这是真的吗?如果是,是在 iOS 中吗?

最佳答案

在 iPhone SDK 上,NSString 上有一系列方法可以提供您想要的内容。

自 iOS 7.0 起,these methods are :

- boundingRectWithSize:options:attributes:context:
- sizeWithAttributes:

在旧版本的 iOS 上,我们有这些,现在已弃用:

– sizeWithFont:  
– sizeWithFont:forWidth:lineBreakMode:  
– sizeWithFont:constrainedToSize:  
– sizeWithFont:constrainedToSize:lineBreakMode:  
– sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode:

关于iOS:如何使用 Quartz 测量字符串的宽度和高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/913470/

相关文章:

ios - 嵌入到选项卡栏 Controller 偏移 TableView

ios - GKScore 排名始终为 0

c++ - Cocos2d-x中"class CC_DLL CCSize"这一行 "CC_DLL"的含义

ios - iOS 中密码字段的字母数字验证

ios - 将项目中的资源组替换为资源目录,构建时代码设计失败

iphone - Apple 是否在任何地方发布应用程序购买系统状态?是否可以确定他们的系统是否/何时停机?

iphone - 如何在 UINavigationBar 上获取 'matte' 颜色?

cocoa-touch - CALayer 和离屏渲染

ios - iOS 上 View 的渐变背景

ios - 如何设置具有延迟的显式 CA 动画的最终值