我正在制作类似于绘图应用程序的应用程序,并希望在用户触摸的位置绘制图像。我可以在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);

但是,每当我再次点击时,图像就会移动到新位置。
我希望每次点击都会“复制”。
我怎样才能做到这一点?

最佳答案

你可以试试看

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

它可以工作。

关于ios - 多个CGContextRefs?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30771017/

10-09 16:16