user1125890
user1125890

Reputation: 71

Core graphics rotate rectangle

With this formula I got angle

double rotateAngle = atan2(y,x)

with this code I can draw a rectangle

CGRect rect = CGRectMake(x,y , width ,height);
CGContextAddRect(context, rect);
CGContextStrokePath(context);

How can I rotate the rectangle around the angle ?

Upvotes: 7

Views: 5035

Answers (1)

Steve
Steve

Reputation: 31642

Here's how you'd do that:

CGContextSaveGState(context);

CGFloat halfWidth = width / 2.0;
CGFloat halfHeight = height / 2.0;
CGPoint center = CGPointMake(x + halfWidth, y + halfHeight);

// Move to the center of the rectangle:
CGContextTranslateCTM(context, center.x, center.y);
// Rotate:
CGContextRotateCTM(context, rotateAngle);
// Draw the rectangle centered about the center:
CGRect rect = CGRectMake(-halfWidth, -halfHeight, width, height);
CGContextAddRect(context, rect);
CGContextStrokePath(context);

CGContextRestoreGState(context);

Upvotes: 30

Related Questions