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

bhz*_*zag 15 ios uibezierpath swift

我有一个实例,UIBezierPath我想将笔画的颜色改为黑色以外的东西.有谁知道如何在Swift中这样做?

Ima*_*tit 38

有了Swift 3,UIColor有一个setStroke()方法.setStroke()有以下声明:

func setStroke()
Run Code Online (Sandbox Code Playgroud)

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

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

strokeColor.setStroke() // where strokeColor is a `UIColor` instance
Run Code Online (Sandbox Code Playgroud)

下面的代码操场展示了如何使用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
Run Code Online (Sandbox Code Playgroud)