2011-03-15 24 views
0

我正在學習Quartz,想要做一個這樣的演示: 當你的手指在iPhone屏幕上移動時,它顯示紅色的軌跡 代碼就像:如何用Quartz2d在iPhone中繪製圖片

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ 
UITouch *touch = [touches anyObject]; 
_firstPoint = [touch locationInView:self]; 
} 

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ 
UITouch *touch = [touches anyObject]; 
_endPoint = [touch locationInView:self]; 
[self setNeedsDisplay]; 
_firstPoint = _endPoint; 
} 

然後

- (void)drawRect:(CGRect)rect { 

// Drawing code. 
CGContextRef _context = UIGraphicsGetCurrentContext(); 

CGContextSetRGBStrokeColor(_context, 1, 0, 0, 1); 
CGContextMoveToPoint(_context, _firstPoint.x, _firstPoint.y); 
CGContextAddLineToPoint(_context, _endPoint.x, _endPoint.y); 

CGContextStrokePath(_context); 
} 

這裏,_firstPoint和_endPoint是CGPoint記錄位置。 但是,它不顯示曲目。 我不知道是什麼問題。 請給任何提示。

最後,我想諮詢是否正確完成這樣一種應用程序。

謝謝!

回答

1

對於您存儲構成線的點集合的位置,它不存儲在此示例中。

EDITED

呀,來存儲它們,我只是添加到NSMutableArray裏。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    if (!_points) _points = [[NSMutableArray array] retain]; 
    UITouch *touch = [touches anyObject]; 
    [_points addObject:[NSValue valueWithCGPoint:[touch locationInView:self]]; 
} 
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [touches anyObject]; 
    [_points addObject:[NSValue valueWithCGPoint:[touch locationInView:self]]; 
    [self setNeedsDisplay]; 
} 

的setNeedsDisplay是要調用這就是你使用點和你的繪圖方法的drawRect。

+0

我不是很瞭解。我是否應該存儲所有點並將其全部繪製在TouchesEnded中?我想如果我移動,並且將點添加到屏幕上以繪製一條線。 – scorpiozj 2011-03-15 05:33:37

+0

我試過了,它工作。謝謝!還有一個問題:在這種情況下,當我移動時,原始上下文的某些部分會受到影響。如何避免這種情況? – scorpiozj 2011-03-16 00:38:37