2010-07-06 147 views
0

我在繪製觸摸手勢上的矩形或三角形時遇到問題。這裏是代碼:在iPhone上繪製圖形

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

    // move the cannon to the touched location 

    x = location.x; 

    [self moveCannon]; 

    [self setNeedsDisplay]; 

} 

-(void) moveCannon 
{ 
    // draw the cannot as a triangle for right now 


    CGMutablePathRef path = CGPathCreateMutable(); 
    CGPathMoveToPoint(path, NULL, 20.0f, 100.0f); 
    CGPathAddLineToPoint(path, NULL, 50.0f, 100.0f); 
    CGPathAddLineToPoint(path, NULL, 50.0f, 20.0f); 
    CGPathAddLineToPoint(path, NULL, 50.0f, 100.0f); 
    CGPathCloseSubpath(path); 

    CGContextSetFillColorWithColor(self.context, [UIColor redColor].CGColor); 
    CGContextAddPath(self.context, path); 
    CGContextFillPath(self.context); 

} 

我錯過了什麼?

回答

2

我看到兩個可能的問題。首先,您應該在視圖的drawRect方法中繪製大炮,而不是在處理事件時繪製大炮。當前代碼繪製路徑,然後發佈重新顯示事件,這可能導致大炮被擦除。

另一個可能的問題是,即使你存儲的位置,你永遠不會實際使用它。所以如果你的大炮出現,但不移動,這就是爲什麼。

希望這會有所幫助。

+0

發現問題是因爲我沒有正確調用我的自定義方法。 – azamsharp 2010-07-06 12:24:08