iconFont
iconFont是利用图标生成的字体,是一种矢量图。原理与汉字和emoji一样, 每一个图标对应一个unicode
编码。
使用iconFont可以有助于IPA瘦身、适配。
如何使用IconFont
静态注册
- 将字体文件拖入项目
- 配置.plist文件
- 在.plist文件中添加新属性“Fonts provided by application”,该属性的值是一个数组,这意味着可以在这里注册多个字体
动态注册
以.ttf与.json(保存了unicode与name的对应关系)结合使用为例:
private func registerNewFont(ttfFilePath: String, isCustomize: Bool = true) -> CGFont? {
let ttfUrl = URL(fileURLWithPath: ttfFilePath)
if let fontDataProvider = CGDataProvider(url: ttfUrl as CFURL), let fontRef = CGFont(fontDataProvider) {
let r = CTFontManagerRegisterGraphicsFont(fontRef, nil)
if r == true, isCustomize == true, let fullname = fontRef.fullName {
customizeFontUrls.append(ttfUrl)
customizeFontNames.append(fullname as String)
}
return fontRef
}
return nil
}
private func registerNewIconfont(ttfFilePath: String, JSONFilePath: String, isCustomize: Bool = true) -> Bool {
if let font = registerNewFont(ttfFilePath: ttfFilePath, isCustomize: isCustomize) {
return updateIconinfoModels(font: font, JSONFilePath: JSONFilePath)
}
return false
}
private func unregisterCustomizeFonts() -> Bool {
let r = CTFontManagerUnregisterFontsForURLs(customizeFontUrls as CFArray, CTFontManagerScope.none, nil)
if r {
customizeFontNames.removeAll()
customizeFontUrls.removeAll()
let keys = iconinfoModels.keys
keys.forEach {
iconinfoModels.removeValue(forKey: $0)
}
}
return r
}
private func updateIconinfoModels(font: CGFont, JSONFilePath: String, isCustomize: Bool = true) -> Bool {
if let data = try? Data(contentsOf: URL(fileURLWithPath: JSONFilePath)), let key = font.fullName {
let obj = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
if let dic = obj as? [String : Any], let icons = dic["glyphs"] as? [[String : Any]] {
iconinfoModels[key as String] = icons.map { (icon: [String : Any]) -> IconinfoModel in
return IconinfoModel(infoDic: icon)
}
return true
}
}
return false
}
func getIconfontInfo(iconName: String) -> (unicode: String, fontname: String)? {
var tmps = [(unicode: String, fontname: String)]()
_ = iconinfoModels.filter { (key: String, value: [XPSCustomizeFontService.IconinfoModel]) -> Bool in
if let first = value.first(where: { return $0.name == iconName }) {
tmps.append((unicode: first.unicode, fontname: key))
return true
}
return false
}
//资源包下发
if tmps.count == 1 {
return tmps[0]
}
else if tmps.count > 1 {
return tmps.first { $0.fontname != XPSCustomizeFontService.materialIconfontName}
}
return nil
}
网友评论