2016-02-12 76 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圖像。