Oblique text: Creating NSFont with a textTransform changes the size to 1 pt

24 Views Asked by At

I need to correctly display text from older documents in an NSTextView. They used italics to indicate important info, even on fonts that don't have a dedicated italic face.

I tried NSAttributedString's addAttribute(.obliqueness, ..., but not only is that deprecated, it also seems to no longer do anything since TextKit 2 landed. So I tried changing the text transform, but that just makes that range of text 1pt in size, even though the font descriptor contains a pointSize of 12pt.

Am I doing something wrong? Is there an alternative way to get oblique text?

if characterStyle.contains(.italic) {
    let newFont = NSFontManager.shared.convert(font, toHaveTrait: .italicFontMask)
    if NSFontManager.shared.traits(of: newFont).contains(.italicFontMask) {
        return newFont
    } else {
        let obliqueTransform = AffineTransform(m11: 1, m12: tan(Angle(degrees: 0.0).radians),
                                   m21: tan(Angle(degrees: 20.0).radians), m22: 1, tX: 0, tY: 0)
        return NSFont(descriptor: font.fontDescriptor, textTransform: obliqueTransform) ?? font
    }
}

PS - I also tried to do the same with CTFont. Same problem. Not very surprising, as CTFont and NSFont are toll-free bridged, but it was worth a try.

0

There are 0 best solutions below