色调图像与两种不同的颜色

时间:2017-10-05 08:34:01

标签: ios swift uiimage

我有一个有两种颜色的图像:圆圈中心填充红色,周围有白色圆圈。

enter image description here

有没有办法用两种不同颜色着色该图像?例如:用绿色填充内圈,用蓝色填充外圈。

是否可以仅为外圈改变颜色?

着色图像:

let image = UIImage(named: "circles")?.tintWithColor(UIColor.red)

始终更改两个圆圈的颜色。

1 个答案:

答案 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)
    }


}

如何使用

  1. 从故事板中取出UIView并分配课程。
  2. enter image description here

    1. 现在使用属性

      • StrokeWidth:外圈宽度。

      • StrokeColor:外圈颜色。

      • outerFillColor:外圈填充色。

      • innerWidth:内圈宽度。

      • innerFillColor:内圈填充色。

      • bgcolor: uiview的背景颜色,它已在故事板中提供。这是额外的。

    2. enter image description here

      <强>输出

      enter image description here

      现在从故事板中更改更改颜色并检查。属性立即应用于故事板,因此您无需运行该项目。

相关问题