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

时间:2018-10-31 16:22:56

标签: ios swift core-graphics uibezierpath 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点。

enter image description here

1 个答案:

答案 0 :(得分:3)

您正在stroke上调用UIBezierPath,因此您需要使用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
    }
}
相关问题