Swift SVG填充颜色到SVGImage [英] Swift SVG Fil Color to SVGImage

查看:440
本文介绍了Swift SVG填充颜色到SVGImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用SVGKit显示图像

I am using SVGKit to display Images

https://github.com/SVGKit/SVGKit/

如何为SVGImage应用填充颜色

How do I apply fill color for the SVGImage

let namSvgImgVar = SVGKImage(named: namSvgImg)
namSvgImgVar.setFilColor()

要实现此setFilColor函数

want to implement this setFilColor function

推荐答案

希望Swift在其下一个版本中添加此功能

Wish Swift adds this feature in their next release

经过一场噩梦,我想出了以下解决方案
在Swift中使用SVG,该SVG自​​动适合View,并且只需一行代码即可向其中添加填充颜色

After a nightmare, I came up with this solution for
Using SVG in Swift which fits automatically for the View and can add fill colors to it in just one line of code

这是给所有不想像我一样挣扎的人

This is for all who don't wish to struggle like me

| * |用法:

let svgImgVar = getSvgImgFnc("svgImjFileName", ClrVar : ClrVar)

// Can use this Image anywhere in your code

| * |步骤:

我使用了简单的 SwiftSVG 库从SVG文件获取UIView.

I used the simple SwiftSVG library for getting UIView from SVG File

| * |安装 SwiftSVG

|*| Install SwiftSVG Library

1)使用pod进行安装:

1) Use pod to install :

//对于Swift 3

// For Swift 3

pod 'SwiftSVG'

//对于Swift 2.3

// For Swift 2.3

pod 'SwiftSVG', '1.1.5'

2)添加框架

转到AppSettings
->常规标签
->向下滚动到链接的框架和库
->单击加号图标
->选择SVG.framework

Goto AppSettings
-> General Tab
-> Scroll down to Linked Frameworks and Libraries
-> Click on plus icon
-> Select SVG.framework

3)在您的项目中的任何地方添加以下代码

3) Add below code anywhere in your project

func getSvgImgFnc(svgImjFileNameVar: String, ClrVar: UIColor) -> UIImage
{
    let svgURL = NSBundle.mainBundle().URLForResource(svgImjFileNameVar, withExtension: "svg")
    let svgVyuVar = UIView(SVGURL: svgURL!)

    /* The width, height and viewPort are set to 100 

        <svg xmlns="http://www.w3.org/2000/svg"
            width="100%" height="100%"
            viewBox="0 0 100 100">

        So we need to set UIView Rect also same
    */

    svgVyuVar.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
    for svgVyuLyrIdx in svgVyuVar.layer.sublayers!
    {
        for subSvgVyuLyrIdx in svgVyuLyrIdx.sublayers!
        {
            if(subSvgVyuLyrIdx.isKindOfClass(CAShapeLayer))
            {
                let SvgShpLyrIdx = subSvgVyuLyrIdx as? CAShapeLayer
                SvgShpLyrIdx!.fillColor = ClrVar.CGColor
            }
        }
    }
    return svgVyuVar.getImgFromVyuFnc()
}

extension UIView
{
    func getImgFromVyuFnc() -> UIImage
    {
        UIGraphicsBeginImageContext(self.frame.size)

        self.layer.renderInContext(UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()
        return image!
    }
}

这篇关于Swift SVG填充颜色到SVGImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆