Search code examples
iosgeometrycgpath

Draw a rectangle inside a circle with respect to its center


I am trying to place a CGPath over a circle at a given angle. The path looks more like a rectangle. When I finished creating my path, I move to the center of the circle and draw the path from it. But I want to place the left-center of the rectangle to align with the center of the circle, not the top-left. I guess, I should calculate the origin of the rectangle with respect to the given angle by applying some formula, I have no idea how to do it.

 //My logic to draw the circle goes here
....
    //My custom rect drawing logic is inside the CreatePath method
    CGPath customRectPath = CreatePath(size);
    context.TranslateCTM(center.X, center.Y);//I am sure this is where I am doing it wrong
    context.RotateCTM((float)(angle));
    context.AddPath(customRectPath);
    context.DrawPath(CGPathDrawingMode.EOFill);

The image should explain what I am trying to say.

enter image description here


Solution

  • TranslateCTM sets the translation of the top-left corner of your rectangle, not the midpoint of the left side (which you want). To do this, simply take away half the rectangle's height from the y-offset:

    context.TranslateCTM(center.X, center.Y - size.Height / 2);