简体   繁体   English

在iPhone上绘制图形

[英]Drawing Graphics on IPhone

I am having problem in drawing a rectangle or triangle on the touch gesture. 我在触摸手势上绘制矩形或三角形时遇到问题。 Here is the code: 这是代码:

-(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);

}

What am I missing? 我想念什么?

I see two possible problems. 我看到两个可能的问题。 First, you should be drawing the cannon in the view's drawRect method, not when handling the event. 首先,您应该在视图的drawRect方法中绘制大炮,而不是在处理事件时绘制。 The current code paints the path and then posts the redisplay event, which could result in the cannon getting erased. 当前代码绘制路径,然后发布重新显示事件,这可能导致大炮被擦除。

The other possible problem is that even though you're storing the location you never actually use it. 另一个可能的问题是,即使您存储的是位置,也从未实际使用过。 So if your cannon shows up but isn't moving that's why. 因此,如果您的加农炮出现了,但没有动,那就是为什么。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM