Soh*_*ard 2 swift swift-package-manager
我想知道目前是否有办法从 Swift 包中加载字体?字体文件在包中,但编译后的程序找不到它们。
Mojtaba Hosseini 的回答是正确的,但为了使用您的包的字体,您还需要注册它们。您可以在结构中使用一些支持功能来完成它...我在我的项目中使用它:
public struct Appearance {
/// Configures all the UI of the package
public static func configurePackageUI() {
loadPackageFonts()
}
static func loadPackageFonts() {
// All the filenames of your custom fonts here
let fontNames = ["Latinotype - Texta-Black.otf",
"Latinotype - Texta-BlackIt.otf",
"Latinotype - Texta-Bold.otf",
"Latinotype - Texta-BoldIt.otf",
"Latinotype - Texta-Book.otf",
"Latinotype - Texta-BookIt.otf",
"Latinotype - Texta-Heavy.otf",
"Latinotype - Texta-HeavyIt.otf",
"Latinotype - Texta-It.otf",
"Latinotype - Texta-Light.otf",
"Latinotype - Texta-LightIt.otf",
"Latinotype - Texta-Medium.otf",
"Latinotype - Texta-MediumIt.otf",
"Latinotype - Texta-Regular.otf",
"Latinotype - Texta-Thin.otf",
"Latinotype - Texta-ThintIt.otf",
]
fontNames.forEach{registerFont(fileName: $0)}
}
static func registerFont(fileName: String) {
guard let pathForResourceString = Bundle.module.path(forResource: fileName, ofType: nil),
let fontData = NSData(contentsOfFile: pathForResourceString),
let dataProvider = CGDataProvider(data: fontData),
let fontRef = CGFont(dataProvider) else {
print("*** ERROR: ***")
return
}
var errorRef: Unmanaged<CFError>? = nil
if !CTFontManagerRegisterGraphicsFont(fontRef, &errorRef) {
print("*** ERROR: \(errorRef.debugDescription) ***")
}
}
}
Run Code Online (Sandbox Code Playgroud)
请记住在数组中添加字体文件名。
从 Swift 5.3 开始,您可以resources向目标添加任何内容,包括图像、资产、字体、zip 等。使用目录名称将包括该目录的所有子文件:
.target(
name: "ABUIKit",
dependencies: [],
resources: [.process("Resources") // <- this will add Resource directory to the target
]
),
Run Code Online (Sandbox Code Playgroud)
请注意,您应该将Resources文件夹放在下面sources/packageName以使其可识别。
您需要注册字体才能使其工作。所以你可以使用像FontBlaster这样的框架。
所以你需要在模块代码的早期注册:
FontBlaster.blast(bundle: .module)
Run Code Online (Sandbox Code Playgroud)
然后你可以在模块内部甚至外部使用字体!
| 归档时间: |
|
| 查看次数: |
840 次 |
| 最近记录: |