Gizmodo
Gizmodo

Reputation: 3222

Font Character Height Change in iOS

I am trying to see if there is a proper method to change the height of the text, without changing the width - more akin to vertical compression. Photoshop lets you do it as shown below:

enter image description here

There are methods to change different attributes in text with NSAttributedString, but I didn't see one to change the height listed here:

https://developer.apple.com/documentation/foundation/nsattributedstring/key

Upvotes: 0

Views: 50

Answers (1)

DonMag
DonMag

Reputation: 77433

You can do this by applying a scale CGAffineTransform.

Quick example using two identical labels, each with font set to .systemFont(ofSize: 32.0, weight: .regular), but the second label scaled to 50% height:

class ScaledLabelVC: UIViewController {
    
    let v1 = UILabel()
    let v2 = UILabel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        [v1, v2].forEach { v in
            v.text = "This is a string."
            v.font = .systemFont(ofSize: 32.0, weight: .regular)
            v.backgroundColor = .yellow
            v.translatesAutoresizingMaskIntoConstraints = false
            view.addSubview(v)
        }
        
        let g = view.safeAreaLayoutGuide
        NSLayoutConstraint.activate([
            
            v1.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
            v1.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
            v1.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
            
            v2.topAnchor.constraint(equalTo: v1.bottomAnchor, constant: 8.0),
            v2.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
            v2.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),

        ])
        
        v2.transform = CGAffineTransform(scaleX: 1.0, y: 0.5)
        
    }
    
}

Result:

enter image description here

Upvotes: 1

Related Questions