IconFont 的使用#
github 連結#
背景: 最近設計提了要求,切圖用 IconFont#
一開始,在搜了 IconFont 的使用後,選中了 TBCityIconFont,使用了之後,發現對於圖片的支持不太好,就是長寬不等的圖片,顯示的時候會被截斷,在具體實現裡也沒發現修改的地方。
然後就 pass 了,換了另一個 Swift 的 Iconic 的第三方庫,這個庫有個好處,是可以自動把.ttf 文件裡的 Icon 生成一個枚舉使用的時候特別方便。然而缺點是安裝的時候麻煩,之前只是稍微麻煩,最近變得特別麻煩,需要設置 FONT_PATH。而且不支持最新版本的 Swift,每次更新.ttf 字體文件,都要改一次。
實在是受不了了,今天就抽空自己寫 (抄) 了一個。😄有興趣的可以自己看參考連結,其實就是參考連結裡內容的整合。
實現#
首先,我想要的是,傳入一個 Int 類型 (eg: 0xe654) 或者字符串類型 (eg :\u {E61A}) 都支持。 然後如果是本地的文件,我希望可以不用手動收入 unicode 碼。最後就是圖片支持寬高不等的顯示。
整體的原理是Working with icon fonts in iOS. Code example in Swift 3.和github Iconic的結合。
-
首先是傳入類型的支持,定義兩個類方法,一個傳入 Int,一個傳入 String,然後再實現一個 Int->String 的方法,然後根據 String 實現具體內容。
-
本地文件每次收入 unicode 碼不方便,定義兩個枚舉類型,一個是 enum string,一個是 enum UInt32,定義 UInt32 是為了可以兼容 OC。如果純 Swift 只需要使用 enum String 即可。
-
圖片寬高不等的顯示:關鍵代碼如下
...xxx
var rect = CGRect(origin: CGPoint.zero, size: size)
rect.origin.y -= edgeInsets.top
rect.size.width -= edgeInsets.left + edgeInsets.right // 運算符優先級注意
rect.size.height -= edgeInsets.top + edgeInsets.bottom
...xxx
使用#
-
將 MWIconFont.Swift 添加到項目中
-
修改文件中兩個地方,
- 使用
Swift label 使用,生成 attributeString
// 使用枚舉Str
let attributeStr = MWIconFont.attributedString(fromIconStr: MWFontIcon.yuedufuHuodeIcon.rawValue, size: 50.0, color: UIColor.red)
displayLabel.attributedText = attributeStr
// 使用枚舉Int
let attributeStr1 = MWIconFont.attributedString(fromIconInt: MWFontIconInt.yuedufuHuodeIcon.rawValue, size: 50.0, color: UIColor.blue)
displayLabel.attributedText = attributeStr1
OC label 使用,生成 attributeString
NSMutableString *jiantouStr = [MWIconFont attributedStringFromIconInt:MWFontIconIntZuojiantouIcon size:CGSizeMake(19.0, 19.0) color:[UIColor redColor]];
Swift 生成 image
// 使用枚舉Str
let image = MWIconFont.image(fromIconStr: MWFontIcon.yuedufuHuodeIcon.rawValue, size: CGSize(width: 30.0, height: 50.0), color: UIColor.cyan, edgeInsets: UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: -10.0))
displayImageView.image = image
// 使用枚舉Int
let image1 = MWIconFont.image(fromIconInt: MWFontIconInt.yuedufuHuodeIcon.rawValue, size: CGSize(width: 30.0, height: 50.0), color: UIColor.blue, edgeInsets: UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: -10.0))
displayImageView.image = image1
OC 生成 image
UIImage *backIcon = [MWIconFont imageFromIconInt:MWFontIconIntZuojiantouIcon size:CGSizeMake(19.0, 19.0) color:[UIColor redColor]];