多个 CGContextRefs?

Multiple CGContextRefs?

我正在制作一个类似于绘图应用程序的应用程序,并希望在用户触摸的地方绘制图像。我可以在 O.K 位置绘制图像。使用此代码:

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);

但是,每当我再次点击时,图像都会移动到新位置。 我希望它每次被点击时都 "duplicate"。 我该怎么做?

你可以试试这个。

- (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];
}

它可以工作。