在iPhone上绘制图形

时间:2010-07-06 03:30:50

标签: 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);

}

我错过了什么?

1 个答案:

答案 0 :(得分:2)

我看到两个可能的问题。首先,您应该在视图的drawRect方法中绘制大炮,而不是在处理事件时。当前代码绘制路径,然后发布重新显示事件,这可能导致大炮被删除。

另一个可能的问题是,即使您存储了您从未实际使用过的位置。所以,如果你的大炮出现但是没有移动那就是原因。

希望这有帮助。

相关问题