Search code examples
iosquartz-2dcgcontext

Positioning Pre-made CGPath Inside CGContext


I am trying to figure out a way to add or append a path (that I already have made) and somehow be able to set the location of where the path is drawn.

Here's an example of what I'm talking about:

//everything here can be compiled in a regular UIViewController
//this example is very trivial but it illustrates basically what I want to do
CGRect preMadeRect = CGRectMake(0.0f, 0.f, 50.f, 50.f);
CGPathRef preMadePath = CGPathCreateWithEllipseInRect(preMadeRect, NULL);

UIGraphicsBeginImageContext(self.view.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();

//I thought that maybe if I moved to a new point
//the path would respect the starting point as its new 
//x and y coordinates
CGContextMoveToPoint(context, 50.f, 50.f);
//I am adding a path
//I want the path to be positioned at new coordinates
//within the context
CGContextAddPath(context, preMadePath);
CGContextStrokePath(context);

UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

UIImageView *imageView = [[UIImageView alloc]initWithImage:resultImage];
[self.view addSubview: imageView];

Any ideas would be appreciated.


Solution

  • You can't change the points in the path; they are set. However, you can apply a transformation to the context, changing the coordinate system instead.

    Your path defines a rectangle with one corner at the origin (0,0). By default, the origin is in the top-left (or bottom-left) corner of the image. If you translate the coordinate system of the context by 50,50, then draw the path (still at 0,0), it will appear fifty pixels away from the corner.

    Look up CGContextTranslateCTM in the documentation.

    You might also need to use CGContextSaveGState and CGContextRestoreGState if you are doing other drawing and need to undo the coordinate system changes.