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
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With