Swift or Objective-C IconFont 字型的使用

來源:互聯網
上載者:User

標籤:src   span   3.0   圖片   list   phi   uil   screen   lan   

IOS可以直接使用單個icon(svg,png)。也可以直接引入字型應用:

1:將您從IconFont平台下載的字型檔(.ttf)添加到工程中;

開啟Info.plist檔案,增加一個新的Array類型的鍵,鍵名設定為UIAppFonts(Fonts provided by application),增加字型的檔案名稱:“iconfont.ttf“

2、Objective-C 使用IconFont字型
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;}

這裡有兩個地方注意下:

  • 建立 UIFont 使用的是字型名,而不是檔案名稱;
  • 文本值為 8 位的 Unicode 字元,我們可以開啟 demo.html 尋找每個表徵圖所對應的 HTML 實體 Unicode 碼,比如: "店" 對應的 HTML 實體 Unicode 碼為:0x3439 轉換後為:\U00003439 就是將 0x 替換為 \U 中間用 0 填補滿長度為 8 個字元
 3、Swift 3.0  使用IconFont字型
 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 這點要注意。

最後,補充 阿里字型向量表徵圖庫

 

Swift or Objective-C IconFont 字型的使用

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.