views:

845

answers:

3

Hello Everyone,

How do I draw a smooth line with a finger slide/touch motion on the iPhone? I have the following code but it is not smooth. It makes corners/turns for example when I try to do a circle. I think I have to use OpenGL. Any ideas? sample code? tutorials?

Thanks!

UIGraphicsBeginImageContext(self.view.frame.size);
[drawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
CGContextSetAllowsAntialiasing(UIGraphicsGetCurrentContext(), YES);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
A: 

You don't need OpenGL. Just keep a reference to the start point and clear the context in touchesMoved, and do something along the lines of:

CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), startPoint.x, startPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());

This will make a straight line from the start point to the current point.

eman
This code will only make a straight line and won't be able to make a cricle, let's say.
lugte098
I suggest you look closer at some of the CGPath functions. For a circle, you could use `CGPathAddArc`, for instance.
eman
@eman: you're missing the question. In Cocoa-touch, when one tries to trace a circle on the screen, one gets touchMoved events for maybe 8, 12 or maybe even 20 points along the user's touch-path. So, when one connects the dots, one gets a jagged 8-, 12- or 20-sided figure, not a nice circle. I believe OP is looking for a way to do curve-smoothing -- perhaps with splines or similar.
Olie
+1  A: 

I ended up using Open GL and a particle. Good example to check out for this is Apple's GLPaint example code.

Erika
A: 

Add this to your code to smooth out the lines between points

CGContextSetLineJoin(UIGraphicsGetCurrentContext(), kCGLineJoinRound);

That'll make a huge difference

levous