My client reached me asking me to add a new line type to the existing iOS app I wrote to them:
I did some research, drawing a curve line is easy, like this post pointed out, all I need is just code like this:
CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetLineWidth(context, 2.0); CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor); CGContextBeginPath(context); CGContextMoveToPoint(context, 100, 100); CGContextAddCurveToPoint(context,125,150,175,150,200,100); CGContextAddCurveToPoint(context,225,50,275,75,300,200); CGContextStrokePath(context);
Now the challenge is, how to calculate the waypoint on the fly when user touched the screen? Time to polish my high school Math skills….
Here is my solution:
- Get start and end points (x1,y1) and (x2, y2)
- Calculating one of the quart point. (x3, y3)
- those 2 angles alpha are the same, and alpha = atan((x2-x1)/(y1-y2))
- the waypoint (x4,y4) is possible to get now, x4 = x3 – sin(alpha) * wave_height, y4 = y4 – cos(alpha) * wave_height.
Here is the end result:
As video shows, when moving speed is not steady, the wavy line looks funny, that’s because I always start from negative sin first, to make it transiting smoother I think I should record the last stopped calculation for (x4,y4), so the continuing calculation will just do the other way. Anyway, this is not an issue when moving speed is steady.