iOS中優雅的使用iconfont

1.什麼是iconfont

    iconFont拆開來看,就是 Icon + Font,這樣估計你們應該都能理解是什麼,那二者結合是什麼呢?沒錯!就是 IconFont !讓開發者像使用字體同樣使用圖標。若是本身不會作的話,能夠直接去阿里的iconfont圖標庫下載本身須要的圖標。html

2.爲何要使用iconfont

    在開發項目時,不可避免的會用到各類圖標,爲了適配不一樣的設備,一般須要@2x和@3x兩套圖,例如說咱們tabBar上使用的圖標。有些app有換膚的須要,還須要多套不一樣的圖來進行匹配不一樣的主題。若是使用切圖,這對於設計和開發來講無疑是增長了工做量,並且ipa的體積也會增大。git

使用iconfont的好處:

1. 減少ipa包的大小
2. 圖標保真縮放,多設備適配一套圖解決問題
3. 適應換膚要求,使用方便。
複製代碼

3.怎麼用iconfont

1. 首先去iconfont圖標庫下載本身須要的圖標。

下載圖片

如圖咱們能夠選擇本身須要的icon加入到購物車,而後加入項目裏,固然你也能夠直接在購物車直接下載,可是這樣只是沒有修改icon爲本身想要的樣式,加入項目中,你能夠本身任意修改icon爲本身想要的樣式。github

1.png

注意:這裏是下載代碼,這樣咱們就能夠在項目中直接使用bash

2.將下載下來的icon資源添加到本身的項目中。

2.png
咱們所須要的就是這個iconfont.ttf,對於這個ttf文件,我想咱們並不陌生吧。新建項目,將這個ttf文件拖入本身的項目裏。

3.png

注意:勾選如圖選項app

接下來配置項目加載這個文件ide

  • 檢查文件是否在項目中,否則會崩潰

4.png

  • 在plist文件中加入字體
    plist
    接下來咱們藉助淘點點科技寫的一個關於iconfont封裝,方便咱們使用iconfont。iconfont的封裝包括
    工具類
  1. TBCityIconInfo.h的實現
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface TBCityIconInfo : NSObject

@property (nonatomic, strong) NSString *text;
@property (nonatomic, assign) NSInteger size;
@property (nonatomic, strong) UIColor *color;

- (instancetype)initWithText:(NSString *)text size:(NSInteger)size color:(UIColor *)color;
+ (instancetype)iconInfoWithText:(NSString *)text size:(NSInteger)size color:(UIColor *)color;

@end
複製代碼
  1. TBCityIconInfo.m的實現
#import "TBCityIconInfo.h"

@implementation TBCityIconInfo

- (instancetype)initWithText:(NSString *)text size:(NSInteger)size color:(UIColor *)color {
    if (self = [super init]) {
        self.text = text;
        self.size = size;
        self.color = color;
    }
    return self;
}

+ (instancetype)iconInfoWithText:(NSString *)text size:(NSInteger)size color:(UIColor *)color {
    return [[TBCityIconInfo alloc] initWithText:text size:size color:color];
}

@end
複製代碼
  1. TBCityIconFont.h的實現
#import "UIImage+TBCityIconFont.h"
#import "TBCityIconInfo.h"

#define TBCityIconInfoMake(text, imageSize, imageColor) [TBCityIconInfo iconInfoWithText:text size:imageSize color:imageColor]

@interface TBCityIconFont : NSObject

+ (UIFont *)fontWithSize: (CGFloat)size;
+ (void)setFontName:(NSString *)fontName;

複製代碼
  1. TBCityIconFont.m的實現
#import "TBCityIconFont.h"
#import <CoreText/CoreText.h>

@implementation TBCityIconFont

static NSString *_fontName;

+ (void)registerFontWithURL:(NSURL *)url {
    NSAssert([[NSFileManager defaultManager] fileExistsAtPath:[url path]], @"Font file doesn't exist");
    CGDataProviderRef fontDataProvider = CGDataProviderCreateWithURL((__bridge CFURLRef)url);
    CGFontRef newFont = CGFontCreateWithDataProvider(fontDataProvider);
    CGDataProviderRelease(fontDataProvider);
    CTFontManagerRegisterGraphicsFont(newFont, nil);
    CGFontRelease(newFont);
}

+ (UIFont *)fontWithSize:(CGFloat)size {
    UIFont *font = [UIFont fontWithName:[self fontName] size:size];
    if (font == nil) {
        NSURL *fontFileUrl = [[NSBundle mainBundle] URLForResource:[self fontName] withExtension:@"ttf"];
        [self registerFontWithURL: fontFileUrl];
        font = [UIFont fontWithName:[self fontName] size:size];
        NSAssert(font, @"UIFont object should not be nil, check if the font file is added to the application bundle and you're using the correct font name.");
    }
    return font;
}

+ (void)setFontName:(NSString *)fontName {
    _fontName = fontName;
    
}


+ (NSString *)fontName {
    return _fontName ? : @"iconfont";
}

@end
複製代碼
  1. UIImage+TBCityIconFont.h的實現
#import <UIKit/UIKit.h>
#import "TBCityIconInfo.h"

@interface UIImage (TBCityIconFont)

+ (UIImage *)iconWithInfo:(TBCityIconInfo *)info;

@end
複製代碼
  1. UIImage+TBCityIconFont.m的實現
#import "UIImage+TBCityIconFont.h"
#import "TBCityIconFont.h"
#import <CoreText/CoreText.h>

@implementation UIImage (TBCityIconFont)

+ (UIImage *)iconWithInfo:(TBCityIconInfo *)info {
    CGFloat size = info.size;
    CGFloat scale = [UIScreen mainScreen].scale;
    CGFloat realSize = size * scale;
    UIFont *font = [TBCityIconFont fontWithSize:realSize];
    UIGraphicsBeginImageContext(CGSizeMake(realSize, realSize));
    CGContextRef context = UIGraphicsGetCurrentContext();
 
    if ([info.text respondsToSelector:@selector(drawAtPoint:withAttributes:)]) {
        /**
         * 若是這裏拋出異常,請打開斷點列表,右擊All Exceptions -> Edit Breakpoint -> All修改成Objective-C
         * See: http://stackoverflow.com/questions/1163981/how-to-add-a-breakpoint-to-objc-exception-throw/14767076#14767076
         */
        [info.text drawAtPoint:CGPointZero withAttributes:@{NSFontAttributeName:font, NSForegroundColorAttributeName: info.color}];
    } else {
        
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        CGContextSetFillColorWithColor(context, info.color.CGColor);
        [info.text drawAtPoint:CGPointMake(0, 0) withFont:font];
#pragma clang pop
    }
    
    UIImage *image = [UIImage imageWithCGImage:UIGraphicsGetImageFromCurrentImageContext().CGImage scale:scale orientation:UIImageOrientationUp];
    UIGraphicsEndImageContext();
    
    return image;
}

@end

複製代碼
3.具體使用方法

1.在AppDelegate.m中,初始化iconfont工具

#import "AppDelegate.h"
#import "TBCityIconFont.h"
#import "ViewController.h"
@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [TBCityIconFont setFontName:@"iconfont"];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[ViewController new]];
   self.window.rootViewController = nav;
    [self.window makeKeyAndVisible];
    return YES;
}
複製代碼
  1. ViewController.m中實現
#import "ViewController.h"
#import "TBCityIconFont.h"
#import "UIImage+TBCityIconFont.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor  whiteColor];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 30, 30)];
    [self.view addSubview:imageView];
    //圖標編碼是&#xe600,須要轉成\U0000e600
    imageView.image = [UIImage iconWithInfo:TBCityIconInfoMake(@"\U0000e600", 30, [UIColor redColor])];
    
    
    //    button
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(100, 150, 40, 40);
    [self.view addSubview:button];
    [button setImage:[UIImage iconWithInfo:TBCityIconInfoMake(@"\U0000e614", 40, [UIColor redColor])] forState:UIControlStateNormal];
    
    //    label,label能夠將文字與圖標結合一塊兒,直接用label的text屬性將圖標顯示出來
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 200, 280, 40)];
    [self.view addSubview:label];
    label.font = [UIFont fontWithName:@"iconfont" size:15];//設置label的字體
    label.text = @"在lable上顯示 \U0000e658";
    
    

    // Do any additional setup after loading the view, typically from a nib.
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
複製代碼

結果以下圖所示:字體

5.png

注意: 1. 所用到的unicode編碼須要本身手動將&#xXXXX格式轉換成\UXXXXXXXX格式,例如//圖標編碼是&#xe600,須要轉成\U0000e600 2. 全部須要的unicode編碼均可以在下載的iconfont文件夾中的.html文件打開查看 ui

6.png

本文demo,歡迎批評指正,留下你的star哦。 更多文章請點擊這裏編碼

若有須要,請關注公衆號JackerooChu,瞭解更多文章

公衆號
相關文章
相關標籤/搜索