我为它创建了一个扩展:
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
}