图像上的CGcontext绘图不起作用

时间:2016-02-12 08:14:54

标签: ios objective-c cgcontext touchesbegan touchesmoved

这是我的代码,它在执行时会产生一个非常奇怪的图形。此外,图像视图开始逐渐消失。请帮帮我这个

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


}

此外,它绘制的线条形状怪异,并且它们不断消失

1 个答案:

答案 0 :(得分:0)

你的图像正在移动,因为你在每次重绘时都有44个点的硬编码偏移。

奇怪的绘图很可能是坐标系统使用无效的结果。您在视图坐标中接收触摸位置,但绘制图像坐标。解决此问题的最简单方法是创建大小等于视图大小而不是图像大小的上下文。只需使用imageView.bounds.size代替imageView.image.size即可。请注意,我假设您使用&#34;缩放以填充&#34;图像视图中的模式。

更改后的整个绘图代码:

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图像。