我正在創建一個簡單的繪圖應用程序,並希望根據用戶的觸摸事件繪製矩形。我可以使用Core Graphics從touchesBegan到touchesEnded中的點繪製矩形。這個矩形會在觸發touchesEnded事件後顯示。使用Core Graphics和實時預覽繪製矩形
但是,我希望能夠以'現場'的方式做到這一點。意思是,當用戶拖動他們的手指時,矩形被更新並顯示。這可能嗎?任何幫助將不勝感激,謝謝!
UPDATE:
我能得到這個使用下面的代碼工作。它適用於小圖像,但它對於大圖像非常緩慢。我意識到我的解決方案效率非常低,想知道是否有人可以提出更好的解決方案。謝謝。
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
_firstPoint = [touch locationInView:self.view];
_firstPoint.y -= 40;
_lastPoint = _firstPoint;
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self.view];
currentPoint.y -= 40;
[self drawSquareFrom:_firstPoint to:currentPoint];
_lastPoint = currentPoint;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self.view];
currentPoint.y -= 40;
[self drawSquareFrom:_firstPoint to:currentPoint];
[_modifiedImage release];
_modifiedImage = [[UIImage alloc] initWithCGImage:_imageView.image.CGImage];
}
- (void)drawSquareFrom:(CGPoint)firstPoint to:(CGPoint)lastPoint
{
_imageView.image = _modifiedImage;
CGFloat width = lastPoint.x - firstPoint.x;
CGFloat height = lastPoint.y - firstPoint.y;
_path = [UIBezierPath bezierPathWithRect:CGRectMake(firstPoint.x, firstPoint.y, width, height)];
UIGraphicsBeginImageContext(_originalImage.size);
[_imageView.image drawInRect:CGRectMake(0, 0, _originalImage.size.width, _originalImage.size.height)];
_path.lineWidth = 10;
[[UIColor redColor] setStroke];
[[UIColor clearColor] setFill];
[_path fill];
[_path stroke];
_imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
爲什麼不創建CALayer對象組合的圖像,而不是繪製到位圖圖像中? (例如,Illustrator與Photoshop)在這種情況下,您可以輕鬆地將CAShapeLayer與矩形路徑添加到您的文檔中。當用戶完成拖動時將其提交到文檔。 – nielsbot 2013-01-06 01:48:42
在任何情況下,您都可以在文檔視圖中使用帶有矩形路徑的CAShapeLayer預覽當前圖像。 – nielsbot 2013-01-06 01:49:09