绘制到 CGContext 时如何设置 UIBezierPath 的线宽?

How do I set the line width of a UIBezierPath when drawing to a CGContext?

我正在尝试使用提供的 UIBezierPath 创建 UIImage。不幸的是,无论我将 setLineWidth 设置为什么,结果始终是 1 点的笔画:

extension UIBezierPath {
    func image(fillColor: UIColor, strokeColor: UIColor) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(bounds.size, false, 1.0)
        guard let context = UIGraphicsGetCurrentContext() else {
            return nil
        }

        context.setLineWidth(10)
        context.setFillColor(fillColor.cgColor)
        context.setStrokeColor(strokeColor.cgColor)

        self.fill()
        self.stroke()

        let image = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        return image
    }
}

在一个带有圆圈的测试项目中进行尝试,例如:

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let imageView = UIImageView()
        imageView.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
        view.addSubview(imageView)

        let bezierPath = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 100, height: 100))

        let image = bezierPath.image(fillColor: UIColor.blue, strokeColor: UIColor.red)

        imageView.image = image
    }
}

无论我将 setLineWidth 设置为什么,它总是显示为 1 点。

您正在 UIBezierPath 上调用 stroke,因此您需要使用 self.lineWidth = 10.[=15= 设置 lineWidth 属性 ]

extension UIBezierPath {
    func image(fillColor: UIColor, strokeColor: UIColor) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(bounds.size, false, 1.0)
        guard let context = UIGraphicsGetCurrentContext() else {
            return nil
        }

        context.setFillColor(fillColor.cgColor)
        self.lineWidth = 10
        context.setStrokeColor(strokeColor.cgColor)

        self.fill()
        self.stroke()

        let image = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        return image
    }
}