Liam Keeley
Liam Keeley

Reputation: 307

Why Is Angled Line In 'Pie Slice' Not Drawing Correctly With UIBezierPath?

I am trying draw a 'pie slice' in a circle, where one edge is vertical from the top to the center, one edge is an arc from the top point to a point on the circle, and the last edge is from the end of the arc to the center.

Here is the code I am using at the moment:

class ArcView : UIView {
  override func draw(_ rect: CGRect) {
    let x1 = rect.minX
    let x2 = rect.maxX
    let y1 = rect.minY
    let y2 = rect.maxY

    let arc_radius = self.superview!.frame.width/2
    let delta_y = y2-y1
    let delta_x = x2-x1
    let angle = asin(delta_x/arc_radius)

    let center = CGPoint(x:x1, y:y2)
    let top = CGPoint(x:x1, y:y1)

    //draw path
    let path = UIBezierPath()
    path.move(to: top)
    path.addArc(withCenter: center, radius: arc_radius, startAngle: CGFloat.pi/2, endAngle: angle, clockwise: true)
    path.addLine(to: center)
    path.addLine(to: top)
    path.close()


    UIColor.green.setFill()
    path.fill()

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = path.cgPath
    layer.mask = shapeLayer
    }
  }

And when I try to draw this within a given rectangle, this is what I am getting: Where the green section is the view I am making with the class above.

Where the green section is the view I am making with the class above. I like the arc and the vertical line, but I want there to be only one other edge which is a line from the right point of the arc to the center.

Upvotes: 0

Views: 80

Answers (1)

Chris
Chris

Reputation: 8091

I think your top and center calculation is wrong.

Instead of

let center = CGPoint(x:x1, y:y2)
let top = CGPoint(x:x1, y:y1)

Try

let center = CGPoint(x: rect.midX y:rect.midY
let top = CGPoint(x:x1, y:rect.midY)

Upvotes: 1

Related Questions