Swift之测量String文字尺寸

在 Swift 中,NSStringboundingRect(with:context:) 方法对应于 String 类型的 size(withAttributes:) 方法,或者可以直接使用 boundingRect(with:options:attributes:context:) 方法来获取字符串的边界矩形。

使用 boundingRect(with:options:attributes:context:)

以下是如何在 Swift 中使用 String 的相关方法来计算文本的边界矩形的示例:

import UIKit

let text = "Hello, World!"
let font = UIFont.systemFont(ofSize: 17) // 设置字体
let attributes: [NSAttributedString.Key: Any] = [.font: font] // 设置属性

let size = CGSize(width: 200, height: .greatestFiniteMagnitude) // 设置宽度,限制高度

// 计算边界矩形
let boundingRect = text.boundingRect(
    with: size,
    options: .usesLineFragmentOrigin,
    attributes: attributes,
    context: nil
)

// 获取结果
print("Bounding rect: \(boundingRect)")

说明

  1. text: 你要测量的字符串。
  2. size: 一个 CGSize,你希望文本在其内计算边界的最大宽度和高度。
  3. options: 一些选项,通常使用 .usesLineFragmentOrigin
  4. attributes: 文本的属性,如字体、颜色等。
  5. context: 用于绘制的上下文,通常可以设置为 nil

注意事项

  • 你可以根据需要调整 size 的宽度和高度,以便适应你的布局需求。
  • 确保在合适的 UI 环境中使用这些方法,通常在 UIViewController 或 UIView 的子类中。
posted @ 2024-09-28 20:14  looxy  阅读(128)  评论(0)    收藏  举报