2017-10-05 79 views
-2

我有兩種顏色的圖像:在中心和白色圓環周圍充滿紅色的圓圈。用兩種不同顏色的色調圖像

enter image description here

有着色兩種不同顏色的圖像的方法嗎?例如:用綠色填充內圈,用藍色填充外圈。

是否可以只爲外圓改變顏色?

着色圖像,如:

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

總是改變兩個圓圈的顏色。

+0

你可以顯示你在問題中描述的圖像。 –

+2

您無法對圖像進行更改,因此請使用UIView。 –

回答

1

你不能像這樣對圖像進行更改,所以使用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和分配類。

enter image description here

  • 現在使用屬性

    • StrokeWidth:外圓寬度。

    • StrokeColor:外圈顏色。

    • outerFillColor:外圈填充顏色。

    • innerWidth:內圈寬度。

    • innerFillColor:內圈填充顏色。

    • 顏色: uiview的背景顏色,它已經在故事板中可用。這是額外的。

  • enter image description here

    輸出

    enter image description here

    現在從故事板改改顏色和檢查。屬性立即應用於故事板,因此您不需要運行該項目。