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

And*_*rew 1 core-graphics cgcontext ios uibezierpath swift

我正在尝试使用提供的 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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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
    }
}
Run Code Online (Sandbox Code Playgroud)

无论我设置什么setLineWidth,它似乎总是 1 分。

在此处输入图片说明

Dáv*_*tor 5

您呼叫strokeUIBezierPath,所以你需要设置lineWidth,使用的财产self.lineWidth = 10

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
    }
}
Run Code Online (Sandbox Code Playgroud)