你好,我正在這個項目上工作,以允許用戶在UIView上的塗鴉。我的方法是創建一個CGMutablePathRef路徑,並在TouchMoved中添加新行。UIView塗鴉 - ios開發
下面列出了相關的代碼,它們在UIView的類中。
static CGMutablePathRef path; //create it as static value.
//I got this habit from java coding but actually not sure
//if it's a good way to do it in objective-c.
//draw the path
-(void)drawRect:(CGRect)rect{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextBeginPath(context);
CGContextAddPath(context, path);
CGContextStrokePath(context);
CGPathRelease(path);
}
//touch began. create the path and add point.
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
path = CGPathCreateMutable();
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:self];
CGPathMoveToPoint(path, NULL, point.x, point.y);
[self setNeedsDisplay];
}
//add points when touch moved
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:self];
CGPathAddLineToPoint(path, NULL, point.x, point.y);
[self setNeedsDisplay];
}
//last points when touch ends
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:self];
CGPathAddLineToPoint(path, NULL, point.x, point.y);
[self setNeedsDisplay];
}
然而,我的錯誤,我不很懂...我想這件事情與UIGestureRecognizer,這是我從其他塗鴉代碼看見。是否有必要添加UIGestureRecognizer?我還沒有學到任何東西,所以我試圖避免使用它。但如果這是必須的,我會試一試。
我想到的另一種方法是將所有點位置存儲到可變數組中,因爲我必須將這些點位置值存儲在某處。但是,我不知道數組是否合適,因爲我沒有找到將浮點值存儲到數組的方法。如果有人能幫助我,這將是非常有幫助的。謝謝!
沒有必要使用UIGestureRecognizers。至於存儲浮動到NSMutableArray看看[[NSNumber](http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/Reference/Reference.html)numberWithFloat: ]。也看看這個問題:http://stackoverflow.com/questions/7393058/how-do-i-use-uibezierpath-to-draw-a-line-that-follows-a-touch-event – 2012-03-28 20:10:59
我' d建議使用手勢識別器。它使你的代碼更簡單,更容易擴展。 – Sven 2012-03-28 20:26:48
@rokjarc是鏈接的問題是非常有幫助的。還有一個小問題:該答案中使用的類是UIImageView,因此在它調用的方法中[self.image drawInRect:CGRectMake(0,0,self.frame.size.width,self.frame.size.height)]。但在我的情況下,它是UIView,所以我應該調用什麼方法來繪製? (對不起,我猜這是一個愚蠢的問題,我真的是一個新手),謝謝! – user1299082 2012-03-31 00:14:50