swift - 将 NSFont 转换为 CGFont——不可能?

标签 swift cocoa core-text

我尝试将 NSFont 转换为 CGFont:

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

像这样:

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

没办法,编译器说“不”:条件向下转换为 CoreFoundation 类型“CGFont”将始终成功。好的,让我们尝试不同的方式:

 let oldFont = defaultFont as CGFont

没有。编译器说“不”:“NSFont”不能转换为“CGFont”;你是不是想用 'as!'强制沮丧?。好的,让我们使用 as!:

 let oldFont = defaultFont as! CGFont

Comppiler 说"is"!但运行时错误说:Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

我尝试按名称启动 CGFont,但并非我所有的字体都“安装在系统中”,如果启动,字体名称可能从 Font-Name 更改为 Font_name通过 CGFont(_ 名称:CFString)。这是有风险的。

有什么帮助吗?

最佳答案

来自 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?

你很接近。从(我认为)Leopard 开始,NSFont 和 CTFontRef(不是 CGFontRef)是免费桥接的,因此您应该能够使用 CTFontCopyGraphicsFont() 从 NSFont 获取 CGFontRef。

例子:

import CoreText

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

关于swift - 将 NSFont 转换为 CGFont——不可能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56893842/

相关文章:

objective-c - fork Cocoa 进程并重新初始化 Cocoa。如何?

ios - 为什么调用 NSMutableAttributedString addAttributes 会崩溃?

ios - Swift 中的 NSGlyph 到 CGGlyph(UInt32 到 UInt16)

ios - AutoLayout 不适用于 Plus 模型

ios - 如果将某种类型传递给 Swift 中的函数,如何返回 nil?

objective-c - Objective C 中最好的多线程方法?

cocoa - "Standard (32/64-bit Intel)"Architecture 作为目标实际上意味着什么?

ios - 动态将自定义字体加载到iOS

ios - swift 2 : UITableView 'reloadSections' method crash in iOS 9

ios - 无法使用图形 API 返回闭包的输出