Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What is going on with this article?
@cayozin

UIFont extension for the optimal fitting of text in a fixed size rectangle

More than 1 year has passed since last update.

Instead of fitting a layout object to contain a text label of fixed size, it is sometimes required to fit the text inside a fixed layout.

In this particular case, we iteratively change the font until it converges on an optimized fit using the instantaneous aspect ratio of the label text. This helps to ensure the label fills the available space as much as possible.

extension UIFont {
    static func createFittedFont(maxWidth: CGFloat, maxHeight: CGFloat, text: String, fontName: String) -> UIFont? {

        let defaultSize: CGFloat = 20
        guard var font = UIFont(name: fontName, size: defaultSize) else {
            print("Error: invalid font name")
            return nil
        }

        let defaultWidth = text.width(withConstraintedHeight: CGFloat.greatestFiniteMagnitude, font: font)
        let defaultHeight = text.height(withConstrainedWidth: CGFloat.greatestFiniteMagnitude, font: font)
        let defaultAspectRatio = defaultHeight / defaultWidth
        let targetAspectRatio = maxHeight / maxWidth

        let eta: CGFloat = 0.03
        let coefficient: CGFloat = 0.4

        while (true) {
            let delta = (targetAspectRatio < defaultAspectRatio) ?
                maxHeight / text.height(
                    withConstrainedWidth: CGFloat.greatestFiniteMagnitude, 
                    font: font) - 1.0
                :
                maxWidth / text.width(
                    withConstraintedHeight: font.pointSize, 
                    font: font) - 1.0

            if(fabs(delta) <= eta) { break }
            let newSize = font.pointSize * (1.0 + coefficient * delta)
            font = font.withSize( newSize )
        }

        return font
    }
}```
0
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
cayozin
iOS/Android development (Swift/C++/Java/Kotlin/XML/Javascript), backend (php/mySQL) and Machine Learning (Python/Scala)
ayudante
いつもユーザー中心で技術者とコンサルタントがとことん考え抜く それがアユダンテです

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
0
Help us understand the problem. What is going on with this article?