2016-02-12 69 views
0

这是我的代码,它在执行时会产生非常奇怪的图形。此外,图像开始逐渐消失,沿着图像视图向下。请帮我这个CGcontext在图像上不起作用

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


} 

此外,该行其绘图怪异的形状,它们正在消失汽车无

回答

0

你的形象正在改变,因为你硬编码在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图像。