2015-08-09 47 views
0

我製作了三角形視圖,名爲UpTriangleView。它用於顯示投票。當他們被挖掘時,我想改變他們的顏色。我想從實例UIColor.grayColor().setStroke(),但我不知道如何做到這一點。如果你知道,請告訴我如何去做。謝謝你的愛。如何在Swift上使用drawRect更改三角形的顏色

class UpTriangleView: UIView { 

    override func drawRect(rect: CGRect) { 
    self.backgroundColor = UIColor.clearColor() 
    // Get Height and Width 
    let layerHeight = self.layer.frame.height 
    let layerWidth = self.layer.frame.width 

    // Create Path 
    let line = UIBezierPath() 

    // Draw Points 
    line.moveToPoint(CGPointMake(0, layerHeight)) 
    line.addLineToPoint(CGPointMake(layerWidth, layerHeight)) 
    line.addLineToPoint(CGPointMake(layerWidth/2, 0)) 
    line.addLineToPoint(CGPointMake(0, layerHeight)) 
    line.closePath() 

    // Apply Color 
    UIColor.grayColor().setStroke() 
    UIColor.grayColor().setFill() 
    line.lineWidth = 3.0 
    line.fill() 
    line.stroke() 

    // Mask to Path 
    let shapeLayer = CAShapeLayer() 
    shapeLayer.path = line.CGPath 
    self.layer.mask = shapeLayer 
    } 
} 


class QATableViewCell : UITableViewCell{ 
    @IBOutlet weak var upTriangleView: UpTriangleView! 
} 

回答

6

屬性添加到您的UpTriangleView就是要繪製它的顏色。實施didSet並調用setNeedsDisplay()如果顏色設置:

class UpTriangleView: UIView { 

    var color = UIColor.gray { 
     didSet { 
      self.setNeedsDisplay() 
     } 
    } 

    override func draw(_ rect: CGRect) { 
     self.backgroundColor = .clear 

     // Get Height and Width 
     let layerHeight = self.layer.bounds.height 
     let layerWidth = self.layer.bounds.width 

     // Create Path 
     let line = UIBezierPath() 

     // Draw Points 
     line.move(to: CGPoint(x: 0, y: layerHeight)) 
     line.addLine(to: CGPoint(x: layerWidth, y: layerHeight)) 
     line.addLine(to: CGPoint(x: layerWidth/2, y: 0)) 
     line.addLine(to: CGPoint(x: 0, y: layerHeight)) 
     line.close() 

     // Apply Color 
     color.setStroke() 
     color.setFill() 
     line.lineWidth = 3.0 
     line.fill() 
     line.stroke() 

     // Mask to Path 
     let shapeLayer = CAShapeLayer() 
     shapeLayer.path = line.cgPath 
     self.layer.mask = shapeLayer 
    } 
} 

現在,演示它在一個遊樂場(見下圖的結果):

let utv = UpTriangleView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) 
utv.color = .yellow // now triangle is yellow 
utv.color = .red  // now triangle is red 

setNeedsDisplay會告訴你的視圖需要重繪iOS和將使用新設置的顏色再次調用drawRect

Picture of triangle in Playground

+0

謝謝vacawama !!我懂了!!!! – lalala

+0

謝謝vacawama ...它像一個魅力工作...真的很有幫助。 –

相關問題