我有一个有两种颜色的图像:圆圈中心填充红色,周围有白色圆圈。
有没有办法用两种不同颜色着色该图像?例如:用绿色填充内圈,用蓝色填充外圈。
是否可以仅为外圈改变颜色?
着色图像:
let image = UIImage(named: "circles")?.tintWithColor(UIColor.red)
始终更改两个圆圈的颜色。
答案 0 :(得分:2)
你无法像这样对图像进行更改,所以请使用UIView。
使用此自定义类
import UIKit
@IBDesignable
class CircleView: UIView {
@IBInspectable var strokeWidth: CGFloat = 0
@IBInspectable var outerFillColor: UIColor = UIColor.clear
@IBInspectable var innerFillColor: UIColor = UIColor.red
@IBInspectable var strokeColor: UIColor = UIColor.clear
@IBInspectable var innerWidth: CGFloat = 0
@IBInspectable var bgColor: UIColor = UIColor.white {
didSet {
backgroundColor = bgColor
}
}
override func draw(_ rect: CGRect) {
self.backgroundColor = bgColor
let circlePath = UIBezierPath(ovalIn: rect)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
shapeLayer.fillColor = outerFillColor.cgColor
shapeLayer.strokeColor = strokeColor.cgColor
shapeLayer.lineWidth = strokeWidth
self.layer.addSublayer(shapeLayer)
let iFrame = CGRect(x: self.frame.width/2 - innerWidth/2,
y: self.frame.height/2 - innerWidth/2,
width: innerWidth, height: innerWidth)
let innerCirclePath = UIBezierPath(ovalIn: iFrame)
let shapeLayerInner = CAShapeLayer()
shapeLayerInner.path = innerCirclePath.cgPath
shapeLayerInner.fillColor = innerFillColor.cgColor
self.layer.addSublayer(shapeLayerInner)
}
}
如何使用