scorpiozj
scorpiozj

Reputation: 2687

how to draw a picture in iPhone with Quartz2d

I'm studying Quartz now and want to do a demo like this: when your finger moves on the iPhone screen, it shows the track in red color。 The code is like:

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

then

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

Here,_firstPoint and _endPoint are CGPoint to record positions. However, it doesn't show the track. I don't know what is the problem. Please give any tips.

Finally, I'd like to consultant whether it is right to fulfill such a kind of App.

thanks!

Upvotes: 0

Views: 1147

Answers (2)

NWCoder
NWCoder

Reputation: 5266

To your point about where the collection of points making up the lines is stored, it is not stored in this example.

EDITED

Yeah, to store them, I'd just add to a NSMutableArray.

something like

- (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];
 }

The setNeedsDisplay is going to invoke the drawRect that's where you use the points and your draw methods.

Upvotes: 1

Sergnsk
Sergnsk

Reputation: 3303

you can read this tutorial to figured it out - may be it helps

http://www.ifans.com/forums/showthread.php?t=132024

i think you missed CGContextBeginPath(...) first of all

good luck!

Upvotes: 1

Related Questions