本文介绍了如何在Swift中更改UIBezierPath的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 UIBezierPath 的实例,我想将笔划的颜色更改为黑色以外的其他颜色。有没有人知道如何在Swift中执行此操作?

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?

推荐答案

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

With Swift 3, UIColor has a setStroke() method. setStroke() has the following declaration:

func setStroke()



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

Therefore, you can use setStroke() like this:

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






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


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:

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中更改UIBezierPath的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 10:12