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 ri开发者_Go百科ght 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. 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.
精彩评论