Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CGMutablePath.addArc not working in Swift 3?

In Xcode 8 beta 6, some of the functions to add a path changed, including those that add an arc:

func addArc(center: CGPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, clockwise: Bool, transform: CGAffineTransform = default)

Beyond a definition of the function, there is no documentation on Apple's site. I've been unable to get an actual arc from this function, and have been relying on a second version that uses tangents. Can anyone provide a working sample? Could it just be bugged?

Here is a function that is broken by the change:

public class func createHorizontalArcPath(_ startPoint:CGPoint, width:CGFloat, arcHeight:CGFloat, closed:Bool = false) -> CGMutablePath
    {
        // http://www.raywenderlich.com/33193/core-graphics-tutorial-arcs-and-paths

        let arcRect = CGRect(x: startPoint.x, y: startPoint.y-arcHeight, width: width, height: arcHeight)

        let arcRadius = (arcRect.size.height/2) + (pow(arcRect.size.width, 2) / (8*arcRect.size.height));
        let arcCenter = CGPoint(x: arcRect.origin.x + arcRect.size.width/2, y: arcRect.origin.y + arcRadius);

        let angle = acos(arcRect.size.width / (2*arcRadius));
        let startAngle = CGFloat(M_PI)+angle // (180 degrees + angle)
        let endAngle = CGFloat(M_PI*2)-angle // (360 degrees - angle)

        let path = CGMutablePath();
        path.addArc(center: arcCenter, radius: arcRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
        if(closed == true)
        {path.addLine(to: startPoint)}
        return path;
    }
like image 996
GoldenJoe Avatar asked Jan 05 '23 12:01

GoldenJoe


1 Answers

Your Swift code is based on the Objective-C code from http://www.raywenderlich.com/33193/core-graphics-tutorial-arcs-and-paths, where the arc path is created as

CGPathAddArc(path, NULL, arcCenter.x, arcCenter.y, arcRadius,
             startAngle, endAngle, 0);

In particular, 0 is passed as argument to the last parameter bool clockwise. That should be translated to false in Swift, not true:

path.addArc(center: arcCenter, radius: arcRadius,
            startAngle: startAngle, endAngle: endAngle, clockwise: false) 
like image 88
Martin R Avatar answered Jan 13 '23 10:01

Martin R