图像上的 CGcontext 绘图不起作用

CGcontext drawing on image not working

这是我的代码,执行时会生成一个非常奇怪的图形。此外,图像开始随着图像视图的下降而慢慢消失。请帮我解决这个问题

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];

//    if ([touch tapCount] == 2)
//    {
//        imageView.image = nil;
//    }

location = [touch locationInView:touch.view];
lastClick = [NSDate date];

lastPoint = [touch locationInView:self.view];
lastPoint.y -= 0;

[super touchesBegan:touches withEvent:event];
}

-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{mouseSwiped = YES;

UITouch *touch = [touches anyObject];
currentPoint = [touch locationInView:self.view];

UIGraphicsBeginImageContext(imageView.image.size);

[imageView.image drawInRect:CGRectMake(0, 44, imageView.image.size.width, imageView.image.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);

CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0, 1, 0, 1);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());

imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
 //   lastPoint = currentPoint;


}

而且它画的线条形状怪怪的,而且不断消失

您的图像在移动,因为您在每次重绘时将偏移量硬编码为 44 点。

怪异的绘图很可能是无效坐标系使用的结果。您在视图坐标中接收触摸位置,但在图像坐标中绘制。解决此问题的最简单方法是创建大小等于视图大小而不是图像大小的上下文。只需使用 imageView.bounds.size 而不是 imageView.image.size。请注意,我假设您在图像视图中使用 "Scale to Fill" 模式。

修改后的整个绘图代码:

UIGraphicsBeginImageContext(self.imageView.bounds.size);

[self.imageView.image drawInRect:CGRectMake(0, 0, self.imageView.bounds.size.width, self.imageView.bounds.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);

CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0, 1, 0, 1);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), self.lastPoint.x, self.lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());

self.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

此外,您的解决方案在性能方面也不是最优的。我建议在视图中单独绘制路径,而不是在每次触摸移动时更新 imageView 图像。