ios 如何在 Swift 中更改 UIBezierPath 的颜色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25533091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change the color of a UIBezierPath in Swift?
提问by bhzag
I have an instance of UIBezierPath
and I want to change the color of the stroke to something other than black. Does anyone know how to do this in Swift?
我有一个实例,UIBezierPath
我想将笔划的颜色更改为黑色以外的颜色。有谁知道如何在 Swift 中做到这一点?
回答by Imanou Petit
With Swift 5, UIColor
has a setStroke()
method. setStroke()
has the following declaration:
有了 Swift 5,UIColor
就有了setStroke()
方法。setStroke()
有以下声明:
func setStroke()
Sets the color of subsequent stroke operations to the color that the receiver represents.
将后续笔画操作的颜色设置为接收器表示的颜色。
Therefore, you can use setStroke()
like this:
因此,您可以setStroke()
像这样使用:
strokeColor.setStroke() // where strokeColor is a `UIColor` instance
The Playground code below shows how to use setStroke()
alongside UIBezierPath
in order to draw a circle with a green fill color and a light grey stroke color inside a UIView
subclass:
操场下面的代码展示了如何使用setStroke()
一起UIBezierPath
为了画一个圆,一个绿色的填充颜色和内部的浅灰色笔触颜色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
回答by Lehlohonolo_Isaac
Let's assume you want to use the color red instead to stroke a rounded rectangle; This is how you do it in Swift 3 :
假设您想使用红色代替描边圆角矩形;这就是你在 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
The second and last lines of the above code are important in answering your question.I hope this answer is helpful.
上面代码的第二行和最后一行对于回答您的问题很重要。我希望这个回答对您有所帮助。