2014-08-27 88 views
11

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

+6

POB的答案在这里很有帮助,但重要的是要明白Bézier路径本身没有颜色。这是一条曲线的描述。只有笔有颜色,POB的答案全是关于设置笔的颜色。 – 2014-08-27 17:38:46

回答

27

随着Swift 3,UIColor有一个setStroke()方法。 setStroke()有如下声明:

func setStroke() 

设置后续行程操作来接收机表示颜色的颜色。

因此,你可以使用setStroke()这样的:

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

下面的游乐场代码演示了如何使用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 
1

假设你想用红色来代替笔划圆角矩形; 这是你怎么做的雨燕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 

上面代码的第二行和最后一行是在回答你的question.I希望这个答案是有帮助的重要。