Multiple CGContextRefs?

90 views Asked by At

I am making a app similar to a drawing app, and want to draw an image at the place the user touches. I can draw the image at the location O.K. with this code:

CGContextRef ctx = UIGraphicsGetCurrentContext();

CGRect imageRect = CGRectMake(self.locationOfTouch.x, self.locationOfTouch.y, 50, 50);
CGFloat centerX = self.locationOfTouch.x - (imageRect.size.width/2);
CGFloat centerY = self.locationOfTouch.y - (imageRect.size.height/2);
// To center image on touch loc
imageRect.origin.x = centerX;
imageRect.origin.y = centerY;

UIImage * imageImage = [UIImage imageNamed:@"image.png"];
CGImageRef imageRef = imageImage.CGImage;
CGContextBeginPath(ctx);
CGContextDrawImage(ctx, imageRect, imageRef);

But, whenever I tap again, the image moves to the new spot. I would like it to "duplicate" every time it was tapped. How can I do this?

1

There are 1 answers

1
maquanhong On BEST ANSWER

You can try this.

- (void)drawLayer:(CALayer*)layer inContext:(CGContextRef)ctx
{
     CGPoint locationPoint = [self.touch locationInView:self];
     CGRect imageRect = CGRectMake(locationPoint.x, locationPoint.y, 50, 50);
     CGFloat centerX = locationPoint.x - (imageRect.size.width/2);
     CGFloat centerY = locationPoint.y - (imageRect.size.height/2);
     imageRect.origin.x = centerX;
     imageRect.origin.y = centerY;
     UIImage * imageImage = [UIImage imageNamed:@"add.png"];
     UIImageView *imageView = [[UIImageView alloc ] initWithFrame:imageRect];
     imageView.image = imageImage;
     [layer addSublayer:imageView.layer];
}

it can work.