Search code examples
swiftcocoacore-text

Casting NSFont to CGFont — impossible?


I try to cast NSFont to CGFont:

 var defaultFont: NSFont = NSFont.labelFont(ofSize: CGFloat(currentSize))

Like this:

 if let oldFont = defaultFont as? CGFont {...

No way, compiler says ”no”: Conditional downcast to CoreFoundation type 'CGFont' will always succeed. OK, let's try different way:

 let oldFont = defaultFont as CGFont

Nope. Compiler says ”no”: 'NSFont' is not convertible to 'CGFont'; did you mean to use 'as!' to force downcast?. OK, let's use as!:

 let oldFont = defaultFont as! CGFont

Copmpiler says ”yes”!, But runtime error says: Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

I tried initiate CGFont by name, but not all my fonts are "mounted in system", and font name could change from Font-Name to Font_name if its initiated by CGFont(_ name:CFString). It's risky.

Any help?


Solution

  • From https://lists.apple.com/archives/cocoa-dev/2010/Feb/msg00177.html:

    Given an NSFont object how can I extract or create a CGFontRef from it to use directly with CoreGraphics?

    You're close. Starting in (I think) Leopard, NSFont and CTFontRef (not CGFontRef) are toll-free bridged, so you should be able to use CTFontCopyGraphicsFont() to get a CGFontRef from an NSFont.

    Example:

    import CoreText
    
    let defaultFont: NSFont = ...
    let cgFont = CTFontCopyGraphicsFont(defaultFont, nil)