I've tried to rotate my rectangle, but it does not work properly.
Here is part of my code, I found it in another post:
#define DEGREES_TO_RADIANS(x) (M_PI * x / 180.0)
-(void)drawRect:(NSRect)rect
{
CGContextRef cRef = [[NSGraphicsContext currentContext] graphicsPort];
// points[] - this is a CGPoints array, length_one is a double value
CGRect rect_one = CGRectMake(points[0].x, points[0].y, (CGFloat)length_one, 40);
// I've print out the origin of old one and new one
NSLog(@"old rect -- %f, %f", rect_one.origin.x, rect_one.origin.y);
float centerX = rect_one.origin.x + (rect_one.size.width / 2.0);
float centerY = rect_one.origin.y + (rect_one.size.height / 2.0);
CGAffineTransform rotation = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(10));
CGAffineTransform moveAnchor = CGAffineTransformMakeTranslation(centerX, centerY);
CGAffineTransform centeredRotation = CGAffineTransformConcat(moveAnchor, rotation);
CGRect rotatedRect = CGRectApplyAffineTransform(rect_one, centeredRotation);
CGContextAddRect(cRef, rotatedRect);
// new one
NSLog(@"new rect -- %f, %f", rotatedRect.origin.x, rotatedRect.origin.y);
}
And the origin changed a lot even I can not find my new rectangle from the view. Old origin is (x = 263.3, y = 502.8) and the new origin is (x=506.1, y=1132.0) How does this system work especially how to assign the angle of rotation? If possible, could you guys help me brief explain it. Thanks a lot!!!!
As others have said, an
NSRect
orCGRect
is always an axis-aligned rectangle.CGRectApplyAffineTransform
returns the axis-aligned bounding box of the translated rectangle:Note that the new rectangle (the bounding box) is likely to have different dimensions than the original rectangle, if you applied a rotation. This means it's useless to apply a transform to a rectangle if you want to draw the transformed rectangle.
Instead, you need to transform the coordinate system of the graphics context. Think of it like this: you're drawing on a sheet of paper on a desk. You always draw a rectangle that is aligned to the edges of the desk. To draw a rotated rectangle, you rotate the paper, then draw a rectangle as usual. Changing the CTM is like rotating (or moving or shrinking or expanding) the sheet of paper.