How to initialize UIBezierPath to draw a circle in

2019-06-17 19:21发布

问题:

I'm trying to draw a circle in Swift, but when I write my code I get a error "could not find an overload for 'init' that accepts the supplied arguments.

In the class UIBezierPath there is a init function:

 init(arcCenter center: CGPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, clockwise: Bool) -> UIBezierPath

But when I declared this with this code I get the error.. Need I cast any variable to other type? but if I compiled this in iphone 4 I don't get the error, only in iphone 5/5s. How can declare this correctly?

  let arcCenter   = CGPoint(x: CGRectGetMidX(self.bounds), y: CGRectGetMidY(self.bounds))
    let radius      = Float(min(CGRectGetMidX(self.bounds) - 1, CGRectGetMidY(self.bounds)-1))

    let circlePath : UIBezierPath = UIBezierPath(arcCenter: arcCenter, radius: radius, startAngle: -rad(90), endAngle: rad(360-90), clockwise: true)

Thanks!

回答1:

You need to convert values that are passed as arguments in UIBezierPath 's init method to CGFloat, because Swift sees them as Double or Float (let radius).

 let circlePath : UIBezierPath = UIBezierPath(arcCenter: arcCenter, radius: 
CGFloat(radius), startAngle: CGFloat(-rad(90)), endAngle: CGFloat(rad(360-90)), clockwise: true)


回答2:

Swift 3:

let circlePath = UIBezierPath(arcCenter: CGPoint.zero, radius: radius, startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)


回答3:

This can be copypasted into playground:

import UIKit
class Circle: UIView {
    var strokeColor: UIColor
    var fillColor: UIColor
    init(frame: CGRect, strokeColor: UIColor, fillColor: UIColor = .clear) {
        self.strokeColor = strokeColor
        self.fillColor = fillColor
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func draw(_ rect: CGRect) {
        let circlePath = UIBezierPath(arcCenter: CGPoint(x: frame.width / 2, y: frame.height / 2), radius: frame.height / 2, startAngle: CGFloat(0), endAngle: CGFloat.pi * 2, clockwise: true)
        strokeColor.setStroke()
        fillColor.setFill()
        circlePath.lineWidth = 1
        circlePath.stroke()
    }

}


let circle = Circle(frame: CGRect(x: 0, y: 0, width: 100, height: 100), strokeColor: .red, fillColor: .blue)