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

标签 ios swift uibezierpath

我有一个 UIBezierPath 实例,我想将描边的颜色更改为黑色以外的颜色。有谁知道如何在 Swift 中执行此操作?

最佳答案

在 Swift 5 中,UIColor 有一个 setStroke()方法。 setStroke() 具有以下声明:

func setStroke()

Sets the color of subsequent stroke operations to the color that the receiver represents.

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

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

下面的 Playground 代码显示了如何将 setStroke()UIBezierPath 一起使用,以便在 中绘制一个具有绿色填充颜色和浅灰色描边颜色的圆code>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

关于ios - 如何在 Swift 中更改 UIBezierPath 的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25533091/

相关文章:

ios - 这是一个 Swift 错误吗?在 webView 中打开文件

ios - 如何将 subview 添加到父 View 范围之外

ios - 崩溃时未打开 Jira(Jira - Fabric 集成)

ios - 在 UIView 上播放透明视频

ios - 没有 * 候选人产生预期的结果类型 FloatingPointRoundingRule

arrays - 将数据附加到 Swift 中的全局数组

ios - 如何在 Swift 中向响应式网站添加后退按钮

iOS - 设计具有透明背景的自定义 UITextField 的最佳方法

swift - 绘制部分圆

ios - 如何制作一个在 Swift 3.0 中抬起点击手势时执行的函数