2

我正在使用 SVGKit 库将svg渲染到图像视图中。SVG 渲染完美,但问题是我无法填充 SVG 颜色。我在 Objective C 中发现了一些对我没有帮助的例子。这里我使用的是 Swift5。请找到随附的控制器代码。提前致谢。

代码:

let namSvgImgVar: SVGKImage = SVGKImage(named: "camera")
let namImjVar: UIImage = namSvgImgVar.uiImage
imageView.image = namImjVar
4

1 回答 1

1

我为它创建了一个扩展:

extension SVGKImage {

    // MARK:- Private Method(s)
    private func fillColorForSubLayer(layer: CALayer, color: UIColor, opacity: Float) {
        if layer is CAShapeLayer {
            let shapeLayer = layer as! CAShapeLayer
            shapeLayer.fillColor = color.cgColor
            shapeLayer.opacity = opacity
        }

        if let sublayers = layer.sublayers {
            for subLayer in sublayers {
                fillColorForSubLayer(layer: subLayer, color: color, opacity: opacity)
            }
        }
    }

    private func fillColorForOutter(layer: CALayer, color: UIColor, opacity: Float) {
        if let shapeLayer = layer.sublayers?.first as? CAShapeLayer {
            shapeLayer.fillColor = color.cgColor
            shapeLayer.opacity = opacity
        }
    }

    // MARK:- Public Method(s)
    func fillColor(color: UIColor, opacity: Float) {
        if let layer = caLayerTree {
            fillColorForSubLayer(layer: layer, color: color, opacity: opacity)
        }
    }

    func fillOutterLayerColor(color: UIColor, opacity: Float) {
        if let layer = caLayerTree {
            fillColorForOutter(layer: layer, color: color, opacity: opacity)
        }
    }
}

如果您的SVG图像只有一层可着色fillColor,或者fillOutterLayerColor有多个,您可以根据需要对其进行修改。这就是我使用它的方式:

static func getImage(imageName: String, fontSize size: CGSize, fillColor color: UIColor?, opacity: Float = 1.0) -> UIImage? {
    let svgImage: SVGKImage = SVGKImage(named: imageName)
    svgImage.size = size
    if let colorToFill = color {
       svgImage.fillColor(color: colorToFill, opacity: opacity)
    }

   return svgImage.uiImage
}
于 2019-12-28T09:29:03.743 回答