今是昨非

今是昨非

日出江花红胜火,春来江水绿如蓝

iOS使用IconFont

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的结合。

  1. 首先是传入类型的支持,定义两个类方法,一个传入 Int,一个传入 String,然后再实现一个 Int->String 的方法,然后根据 String 实现具体内容。

  2. 本地文件每次收入 unicode 吗不方便,定义两个枚举类型,一个是 enum string,一个是 enum UInt32,定义 UInt32 是为了可以兼容 OC。如果纯 Swift 只需要使用 enum String 即可。

  3. 图片宽高不等的显示:关键代码如下


...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

使用#

  1. 来自iconfont 怎么在 iOS 中使用了
    Screen Shot 2019-05-02 at 18.01.24.png

  2. 将 MWIconFont.Swift 添加到项目中

  3. 修改文件中两个地方,

Screen Shot 2019-05-02 at 18.03.39.png

Screen Shot 2019-05-02 at 18.03.52.png

  1. 使用

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]];

参考链接#

Working with icon fonts in iOS. Code example in Swift 3.

iconfont 怎么在 iOS 中使用了

Iconfont - 阿里巴巴矢量图标库

github Iconic

加载中...
此文章数据所有权由区块链加密技术和智能合约保障仅归创作者所有。