cgcontext rotate rectangle

Domlin picture Domlin · Mar 29, 2013 · Viewed 7.5k times · Source

guys! I need to draw some image to CGContext.This is the relevant code:

CGContextSaveGState(UIGraphicsGetCurrentContext());

CGContextRef ctx = UIGraphicsGetCurrentContext();

CGRect rect = r;

CGContextRotateCTM(ctx, DEGREES_TO_RADIANS(350));
[image drawInRect:r];


CGContextRestoreGState(UIGraphicsGetCurrentContext());

Actually,the rectangle is rotate and display on a area what is not my purpose.I just want to rotate the image and display on the same position. Any ideas ?????

Answer

Peter Hosey picture Peter Hosey · Mar 29, 2013

Rotation is about the context's origin, which is the same point that rectangles are relative to. If you imagine a sheet of graph paper in the background, you can see what's going on more clearly:

Rotated context with graph-paper grid in the background and rectangle in the foreground

The line is the “bottom” (y=0) of your window/view/layer/context. Of course, you can draw below the bottom if you want, and if your context is transformed the right way, you might even be able to see it.

Anyway, I'm assuming that what you want to do is rotate the rectangle in place, relative to an unrotated world, not rotate the world and everything in it.

The only way to rotate anything is to rotate the world, so that's how you need to do it:

  1. Save the graphics state.

  2. Translate the origin to the point where you want to draw the rectangle. (You probably want to translate to its center point, not the rectangle's origin.)

    Translated context with graph-paper background, showing the origin at what will be the center of the rectangle

  3. Rotate the context.

    Translated and rotated context with graph-paper background, showing that the axes have now tilted up as before, but now the translated origin has also moved just as the rectangle did

  4. Draw the rectangle centered on the origin. In other words, your rectangle's origin point should be negative half its width and negative half its height (i.e., (CGPoint){ width / -2.0, height / -2.0 })—don't use the origin it had before, because you already used that in the translate step.

    Rectangle drawn in its position, with graph-paper background and origin lines removed

  5. Restore the gstate so that future drawing isn't rotated.