gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 09:34:39 25 4
gpt4 key购买 nike

我制作了三角形 View ,称为 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!
}

最佳答案

向您的 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
}
}

现在,在 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

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

Picture of triangle in Playground

关于swift - 如何在 Swift 上使用 drawRect 更改三角形图形的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31904659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com