如何在Swift中更改UIBezierPath的颜色?

我有一个UIBezierPath的实例,我想将笔划的颜色更改为黑色以外的其他颜色。 有谁知道如何在Swift中做到这一点?

使用Swift 3, UIColor有一个setStroke()方法。 setStroke()具有以下声明:

 func setStroke() 

将后续笔触操作的颜色设置为接收器表示的颜色。

因此,您可以像这样使用setStroke()

 strokeColor.setStroke() // where strokeColor is a `UIColor` instance 

下面的Playground代码显示了如何在setStroke()旁边使用setStroke() ,以便在UIView子类中绘制一个绿色填充颜色和浅灰色笔触颜色的圆:

 import UIKit import PlaygroundSupport class MyView: UIView { override func draw(_ rect: CGRect) { // UIBezierPath let newRect = CGRect( x: bounds.minX + ((bounds.width - 79) * 0.5 + 0.5).rounded(.down), y: bounds.minY + ((bounds.height - 79) * 0.5 + 0.5).rounded(.down), width: 79, height: 79 ) let ovalPath = UIBezierPath(ovalIn: newRect) // Fill UIColor.green.setFill() ovalPath.fill() // Stroke UIColor.lightGray.setStroke() ovalPath.lineWidth = 5 ovalPath.stroke() } } let myView = MyView(frame: CGRect(x: 0, y: 0, width: 200, height: 300)) PlaygroundPage.current.liveView = myView 

假设您想要使用红色代替笔划圆角矩形; 这就是你在Swift 3中的表现:

  // Drawing the border of the rounded rectangle: let redColor = UIColor.red redColor.setStroke() // Stroke subsequent views with a red color let roundedRectagle = CGRect(x: 0,y: 0, width: 90,height: 20) let rectangleBorderPath = UIBezierPath(roundedRect: roundedRectangle,cornerRadius: 5) roundedRectangle.borderWidth = 1 roundedRectangle.stroke() // Apply the red color stroke on this view 

上面代码的第二行和最后一行对回答你的问题很重要。我希望这个答案很有帮助。