Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOS: how to calculate the size of text to draw BEFORE to create the context?

I need to create an image containing one line of text. But the problem, i first need to create the context (CGBitmapContextCreate) with require the width and the height of the image to have the possibility to later calculate the bounds of the text (via CTLineGetImageBounds). but i want the size of the image = the bounds of the text :( how can i do ?

actually i use

CGBitmapContextCreate
CTLineGetImageBounds
CTLineDraw

maybe it's possible to call CTLineGetImageBounds without a context ?

Note: i m on delphi, it's not really a problem as i can have access to all the API, i just need the function name

like image 457
zeus Avatar asked Jun 07 '16 23:06

zeus


2 Answers

You can calculate the space an NSString will take up based on the font you want to use by doing the following:

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

Where bounding size is the maximum size you want the image to be. Then you can use the calculated size to create your image.

like image 71
Ashley Avatar answered Sep 28 '22 05:09

Ashley


This the could you need to write in order to get the size of the text with the font.

let widthOfLabel = 400.0
let size = font?.sizeOfString(self.viewCenter.text!, constrainedToWidth: Double(widthOfLabel))

You have to use the below extension of the font in order to get the size of the text with the font.

Swift 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
  }
}

Former Swift 2 code:

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
    }
}
like image 26
Sukhdeep Singh Kalra Avatar answered Sep 28 '22 06:09

Sukhdeep Singh Kalra