美文网首页
svg 加载

svg 加载

作者: EnjoyWT | 来源:发表于2024-03-28 09:57 被阅读0次
      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
        }
    }
    
    
    
    1. 文件放到 main bundle 中
    2. 全称调用: UIImage.svgImageNamed("icon_defaultPage_home.svg")

    相关文章

      网友评论

          本文标题:svg 加载

          本文链接:https://www.haomeiwen.com/subject/bwsutjtx.html