IOS能夠直接使用單個icon(svg,png)。也能夠直接引入字體應用:html
打開Info.plist文件,增長一個新的Array類型的鍵,鍵名設置爲UIAppFonts(Fonts provided by application),增長字體的文件名:「iconfont.ttf「app
:
UILabel * label = [[UILabel alloc] initWithFrame:self.view.bounds]; UIFont *iconfont = [UIFont fontWithName:@"uxIconFont" size: 34]; label.font = iconfont; label.text = @"\U00003439 \U000035ad \U000035ae \U000035af \U000035eb \U000035ec"; [self.view addSubview: label];
//通常狀況下,iconfont多用於UIImage類。能夠寫一個UIImage+iconfont的分類來實現icon做爲圖片的功能。
+ (UIImage*)imageWithIcon:(NSString*)iconCode inFont:(NSString*)fontName size:(NSUInteger)size color:(UIColor*)color { CGSize imageSize = CGSizeMake(size, size); UIGraphicsBeginImageContextWithOptions(imageSize, NO, [[UIScreen mainScreen] scale]); UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, size, size)]; label.font = [UIFont fontWithName:fontName size:size]; label.text = iconCode; if(color){ label.textColor = color; } [label.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *retImage = UIGraphicsGetImageFromCurrentImageContext(); return retImage; }
這裏有兩個地方注意下:ide
:
let label = UILabel(frame: CGRect(x: 0, y: 0, width: info.textSize!, height: info.textSize!)) label.font = UIFont(name: "IconFont", size: 25) label.textAlignment = .center label.text = \u{e60a} self.view.addSubview(label)
//通常狀況下,iconfont多用於UIImage類。能夠寫一個分類繼承 UIImage 來實現icon做爲圖片的功能。
open class func iconbWithInfo(_ info: IconInfo) -> UIImage{ let imageSize: CGSize = CGSize(width: info.textSize!, height: info.textSize!) UIGraphicsBeginImageContextWithOptions(imageSize, false, UIScreen.main.scale) let label = UILabel(frame: CGRect(x: 0, y: 0, width: info.textSize!, height: info.textSize!)) label.font = UIFont(name: "IconFont", size: 25) label.textAlignment = .center label.text = info.text if (info.textColor != nil) { label.textColor = info.textColor } label.layer.render(in: UIGraphicsGetCurrentContext()!) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! return image }
注:Swift 使用 Unicode 編碼與 OC 不一樣,Swift 的是 \u{e60a} 而 OC 是 \U0000e60a 這點要注意。svg
最後,補充 阿里字體矢量圖標庫字體