pod 'SVGKit'
扩展
//
// UIImage+SVG.swift
// CMS
// Created by JoyTim on 2024/3/28
// Copyright © 2024 ___ORGANIZATIONNAME___. All rights reserved.
//
import SVGKit
import UIKit
extension UIImage {
/**
Show SVG image
- Parameters:
- name: SVG name
- Returns: SVG image
*/
static func svgImageNamed(_ name: String) -> UIImage? {
guard let svgImage = SVGKImage(named: name) else { return nil }
return svgImage.uiImage
}
/**
Show SVG image
- Parameters:
- name: SVG name
- size: Image size
- Returns: SVG image
*/
static func svgImageNamed(_ name: String, size: CGSize) -> UIImage? {
guard let svgImage = SVGKImage(named: name) else { return nil }
svgImage.size = size
return svgImage.uiImage
}
/**
Show SVG image
- Parameters:
- name: SVG name
- size: Image size
- tintColor: Image color
- Returns: SVG image
*/
static func svgImageNamed(_ name: String, size: CGSize, tintColor: UIColor) -> UIImage? {
guard let svgImage = SVGKImage(named: name) else { return nil }
svgImage.size = size
let rect = CGRect(x: 0, y: 0, width: svgImage.size.width, height: svgImage.size.height)
let alphaInfo = svgImage.uiImage.cgImage?.alphaInfo ?? .none
let opaque = alphaInfo == .noneSkipLast || alphaInfo == .noneSkipFirst || alphaInfo == .none
UIGraphicsBeginImageContextWithOptions(svgImage.size, opaque, svgImage.scale)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
context.translateBy(x: 0, y: svgImage.size.height)
context.scaleBy(x: 1.0, y: -1.0)
context.setBlendMode(.normal)
context.clip(to: rect, mask: svgImage.uiImage.cgImage!)
context.setFillColor(tintColor.cgColor)
context.fill(rect)
let imageOut = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imageOut
}
}
- 文件放到 main bundle 中
- 全称调用: UIImage.svgImageNamed("icon_defaultPage_home.svg")
网友评论