IOS:如何计算要创建上下文的文本大小?

lok*_*oki 7 objective-c cgcontext ios swift

我需要创建一个包含一行文本的图像.但问题是,我首先需要创建上下文(CGBitmapContextCreate),要求图像的宽度和高度有可能以后计算文本的边界(通过CTLineGetImageBounds).但我想要图像的大小=文本的边界:(我该怎么办?

实际上我用

CGBitmapContextCreate
CTLineGetImageBounds
CTLineDraw
Run Code Online (Sandbox Code Playgroud)

也许可以在没有上下文的情况下调用CTLineGetImageBounds?

注意:我在delphi上,这不是一个真正的问题,因为我可以访问所有的API,我只需要函数名称

小智 6

您可以NSString通过执行以下操作,根据要使用的字体计算将占用的空间:

NSString *testString = @"A test string";
CGSize boundingSize = self.bounds.size;
CGRect labelRect = [testString
                    boundingRectWithSize:boundingSize
                    options:NSStringDrawingUsesLineFragmentOrigin
                    attributes:@{ 
                        NSFontAttributeName : [UIFont systemFontOfSize:14]
                                }
                    context:nil];
Run Code Online (Sandbox Code Playgroud)

其中边界大小是您希望图像的最大大小.然后,您可以使用计算的大小来创建图像.


Suk*_*lra 5

您可能需要编写此内容才能获得带有字体的文本大小。

let widthOfLabel = 400.0
let size = font?.sizeOfString(self.viewCenter.text!, constrainedToWidth: Double(widthOfLabel))
Run Code Online (Sandbox Code Playgroud)

您必须使用以下字体扩展名才能获取带有该字体的文本的大小。

斯威夫特5:

extension UIFont {
  func sizeOfString(string: String, constrainedToWidth width: CGFloat) -> CGSize {
    return NSString(string: string).boundingRect(
      with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude),
      options: NSStringDrawingOptions.usesLineFragmentOrigin,
      attributes: [NSAttributedString.Key.font: self],
      context: nil
    ).size
  }
}
Run Code Online (Sandbox Code Playgroud)

以前的 Swift 2 代码:

extension UIFont {
    func sizeOfString (string: String, constrainedToWidth width: Double) -> CGSize {
        return NSString(string: string).boundingRectWithSize(CGSize(width: width, height: DBL_MAX),
                                                             options: NSStringDrawingOptions.UsesLineFragmentOrigin,
                                                             attributes: [NSFontAttributeName: self],
                                                             context: nil).size
    }
}
Run Code Online (Sandbox Code Playgroud)