Skip to content

Instantly share code, notes, and snippets.

@zhaoyk
Last active March 8, 2022 11:12
Show Gist options
  • Save zhaoyk/9823633 to your computer and use it in GitHub Desktop.
Save zhaoyk/9823633 to your computer and use it in GitHub Desktop.
UIFont 与 CTFontRef 互相转换
+ (UIFont *)uifontFromCTFontRef:(CTFontRef)ctFont {
CGFloat pointSize = CTFontGetSize(ctFont);
NSString *fontPostScriptName = (NSString *)CFBridgingRelease(CTFontCopyPostScriptName(ctFont));
UIFont *fontFromCTFont = [UIFont fontWithName:fontPostScriptName size:pointSize];
return fontFromCTFont;
}
+ (CTFontRef)ctFontRefFromUIFont:(UIFont *)font {
CTFontRef ctfont = CTFontCreateWithName((__bridge CFStringRef)font.fontName, font.pointSize, NULL);
return CFAutorelease(ctfont);
}
@ShikiSuen
Copy link

ShikiSuen commented Mar 8, 2022

尝试用机器转 swift 却发现还不能直接用在 Swift 当中。
image

import Foundation
import Cocoa

func NSFont(fromCTFontRef ctFont: CTFont?) -> NSFont? {
    var pointSize: CGFloat? = nil
    if let ctFont = ctFont {
        pointSize = CTFontGetSize(ctFont)
    }
    let fontPostScriptName = CFBridgingRelease(CTFontCopyPostScriptName(ctFont!)) as? String
    let fontFromCTFont = NSFont(name: fontPostScriptName ?? "", size: pointSize ?? 0.0)
    return fontFromCTFont
}

func ctFontRef(from font: NSFont?) -> CTFont? {
    var ctfont: CTFont? = nil
    if let fontName = font?.fontName as CFString? {
        ctfont = CTFontCreateWithName(fontName, font?.pointSize ?? 0.0, nil)
    }
    return (CFAutorelease(ctfont) as! CTFont)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment