views:

448

answers:

2

This should be a simple one, basically I have a few paths drawn with core graphics, and I want to be able to rotate them (for convenience). I've tried using CGContextRotateCTM(context); but it's not rotating anything. Am I missing something?

Here's the source for drawRect

- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSetLineWidth(context, 1.5);
CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
CGContextSetShadow(context, CGSizeMake(0, 1), 0);

CGContextBeginPath(context);

CGContextMoveToPoint(context, 13.5, 13.5);
CGContextAddLineToPoint(context, 30.5, 13.5);
CGContextAddLineToPoint(context, 30.5, 30.5);
CGContextAddLineToPoint(context, 13.5, 30.5);
CGContextAddLineToPoint(context, 13.5, 13.5);

CGContextClosePath(context);

CGContextMoveToPoint(context, 26.2, 13.5);
CGContextAddLineToPoint(context, 26.2, 17.8);
CGContextAddLineToPoint(context, 30.5, 17.8);

CGContextMoveToPoint(context, 17.8, 13.5);
CGContextAddLineToPoint(context, 17.8, 17.8);
CGContextAddLineToPoint(context, 13.5, 17.8);

CGContextMoveToPoint(context, 13.5, 26.2);
CGContextAddLineToPoint(context, 17.8, 26.2);
CGContextAddLineToPoint(context, 17.8, 30.5);

CGContextStrokePath(context);

CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
CGContextSetShadowWithColor(context, CGSizeMake(0, 0), 0, [UIColor clearColor].CGColor);

CGContextFillRect(context, CGRectMake(26.2, 13.5, 4.3, 4.3));
CGContextFillRect(context, CGRectMake(13.5, 13.5, 4.3, 4.3));
CGContextFillRect(context, CGRectMake(13.5, 26.2, 4.3, 4.3));

CGContextRotateCTM(context, M_PI / 4);
}
A: 

Actualy I moved CGContexRotateCTM(context, rotation) to the top of the method, and it works, however I want the rotation to occur around the center point.

Scott Langendyk
To rotate about an arbitrary point, first translate so that point moves to the origin, then rotate, then translate back (by the opposite amount).
phkahler
+3  A: 

Place this before drawing/filling your figure to translate to origin, rotate and then translate back to the point it should appear to rotate around:

static inline float radians(double degrees) { return degrees * PI / 180; }

CGContextTranslateCTM(c, midX, midY);
CGContextRotateCTM(c, radians(-73));
CGContextTranslateCTM(c, -midX, -midY);

Change the angle value passed to CGContextRotateCTM to make the figure point in another direction.

Adam Eberbach
This needs more love, this worked for me and is exactly what i needed
DFectuoso