Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the width of a text string of a specific font and font-size?

People also ask

How is font width calculated?

A font is often measured in pt (points). Points dictate the height of the lettering. There are approximately 72 (72.272) points in one inch or 2.54 cm. For example, the font size 72 would be about one inch tall, and 36 would be about a half of an inch.

How do I measure text size?

Point size measures from the height of the highest ascender (peak) to the baseline of the lowercase x. It then measures from the lowest descender (valley) of the font to the top of the lowercase x. Standardized fonts (e.g. Arial, Times New Roman, Calibri, etc.)

What is font width?

The width of each character is called the set width. The set width includes the width of the actual letter as well as the space needed between each character. A font design with a broad set width looks open while one with a narrow set width looks compact.

How do I get text size in HTML?

In HTML 5, you can just use the Canvas. measureText method (further explanation here). If you want to use the font-size of some specific element myEl , you can make use of the getCanvasFont utility function: const fontSize = getTextWidth(text, getCanvasFont(myEl)); // do something with fontSize here...


Since sizeWithFont is deprecated, I'm just going to update my original answer to using Swift 4 and .size

//: Playground - noun: a place where people can play

import UIKit

if let font = UIFont(name: "Helvetica", size: 24) {
   let fontAttributes = [NSAttributedStringKey.font: font]
   let myText = "Your Text Here"
   let size = (myText as NSString).size(withAttributes: fontAttributes)
}

The size should be the onscreen size of "Your Text Here" in points.


sizeWithFont: is now deprecated, use sizeWithAttributes: instead:

UIFont *font = [UIFont fontWithName:@"Helvetica" size:30];
NSDictionary *userAttributes = @{NSFontAttributeName: font,
                                 NSForegroundColorAttributeName: [UIColor blackColor]};
NSString *text = @"hello";
...
const CGSize textSize = [text sizeWithAttributes: userAttributes];

You can do exactly that via the various sizeWithFont: methods in NSString UIKit Additions. In your case the simplest variant should suffice (since you don't have multi-line labels):

NSString *someString = @"Hello World";
UIFont *yourFont = // [UIFont ...]
CGSize stringBoundingBox = [someString sizeWithFont:yourFont];

There are several variations of this method, eg. some consider line break modes or maximum sizes.


Update Sept 2019

This answer is a much cleaner way to do it using new syntax.

Original Answer

Based on Glenn Howes' excellent answer, I created an extension to calculate the width of a string. If you're doing something like setting the width of a UISegmentedControl, this can set the width based on the segment's title string.

extension String {

    func widthOfString(usingFont font: UIFont) -> CGFloat {
        let fontAttributes = [NSAttributedString.Key.font: font]
        let size = self.size(withAttributes: fontAttributes)
        return size.width
    }

    func heightOfString(usingFont font: UIFont) -> CGFloat {
        let fontAttributes = [NSAttributedString.Key.font: font]
        let size = self.size(withAttributes: fontAttributes)
        return size.height
    }

    func sizeOfString(usingFont font: UIFont) -> CGSize {
        let fontAttributes = [NSAttributedString.Key.font: font]
        return self.size(withAttributes: fontAttributes)
    }
}

usage:

    // Set width of segmentedControl
    let starString = "⭐️"
    let starWidth = starString.widthOfString(usingFont: UIFont.systemFont(ofSize: 14)) + 16
    segmentedController.setWidth(starWidth, forSegmentAt: 3)

Swift-5

Use intrinsicContentSize to find the text height and width.

yourLabel.intrinsicContentSize.width

This will work even you have custom spacing between your string like "T E X T"


Oneliner in Swift 4.2 🔸

let size = "abc".size(withAttributes:[.font: UIFont.systemFont(ofSize: 18.0)])