How to draw a wavy line in iOS app?

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:

wavy line

Steps:

  1. Get start and end points (x1,y1) and (x2, y2)
  2. CalculatingĀ  one of the quart point. (x3, y3)
  3. those 2 angles alpha are the same, and alpha = atan((x2-x1)/(y1-y2))
  4. 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:

Next Step:

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s