gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 08:09:04 25 4
gpt4 key购买 nike

在我问问题之前,这是来自 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com