-
首先 去阿里 https://www.iconfont.cn 去搞定iconfont的文件
-
把下载到本地的icontFont倒入到你的项目中, 记得copy if need
在infoplist中加入你的 .ttf文件
<key>UIAppFonts</key>
<array>
<string>iconfont.ttf</string>
</array>
- 定义一个enum来记录iconfont
public enum IconFont: String {
case version = "\u{e672}"
case info = "\u{e61e}"
case more = "\u{e63a}"
case attachment = "\u{e607}"
case copy = "\u{ef86}"
case dot = "\u{e608}"
case back = "\u{e603}"
}
- 使用的iconfont
Text(IconFont.back.rawValue)
.font(.custom("iconfont", size: 20))
总结下:
- 倒入iconfont文件
- infoplist加入倒入文件的名字
- 枚举各个icon的类型
- 使用 .font(.custom)来展示, 你也可以自己封装一下,方便使用
public extension UIImage
{
/*
//方法一:
UIImage.init(from: iconFont, textColor: .black, size: CGSize.init(width: 25, height: 25))
//方法二:
UIImage.icon(from: iconFont, iconColor: .black, imageSize: CGSize.init(width: 25, height: 25), ofSize: 25)
*/
convenience init(from font: IconFont, textColor: UIColor = .black, backgroundColor: UIColor = .clear, size: CGSize) {
let drawText = font
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.center
let fontSize = min(size.width / 1.28571429, size.height)
let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.iconfont(ofSize: fontSize) ?? UIFont.systemFont(ofSize: 14), .foregroundColor: textColor, .backgroundColor: backgroundColor, .paragraphStyle: paragraphStyle]
let attributedString = NSAttributedString(string: drawText.rawValue, attributes: attributes)
UIGraphicsBeginImageContextWithOptions(size, false , UIScreen.main.scale)
attributedString.draw(in: CGRect(x: 0, y: (size.height - fontSize) * 0.5, width: size.width, height: fontSize))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if let image = image {
self.init(cgImage: image.cgImage!, scale: image.scale, orientation: image.imageOrientation)
} else {
self.init()
}
}
static func icon(from font: IconFont, iconColor: UIColor, imageSize: CGSize, ofSize size: CGFloat) -> UIImage
{
let drawText = font.rawValue
UIGraphicsBeginImageContextWithOptions(imageSize, false, UIScreen.main.scale)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.center
drawText.draw(in: CGRect(x:0, y:0, width:imageSize.width, height:imageSize.height), withAttributes: [.font: UIFont.iconfont(ofSize: size) ?? UIFont.systemFont(ofSize: 14), .paragraphStyle: paragraphStyle, .foregroundColor: iconColor])
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
Image(uiImage: UIImage.icon(from: IconFont.home, iconColor: selected == 0 ? UIColor.init(0x459efc) : UIColor.init(0x999999), imageSize: CGSize(width: 25, height: 25), ofSize: 25))