如何使用Swift上的drawRect更改三角形图的颜色

lal*_*ala 0 drawrect swift

我做了三角视图,叫做UpTriangleView.它用于显示投票.当他们被轻拍时,我想改变他们的颜色.我想UIColor.grayColor().setStroke()从实例中,但我不知道该怎么做.如果你知道的话,请告诉我怎么做.谢谢你的亲属关系.

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!
}
Run Code Online (Sandbox Code Playgroud)

vac*_*ama 8

添加一个属性,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
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,在Playground中演示它(见下面的结果图):

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
Run Code Online (Sandbox Code Playgroud)

setNeedsDisplay将告诉iOS您的视图需要重绘,并将drawRect使用新设置的颜色再次调用.

三角的图片在操场