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);
CGContextMoveToPoint(context, 100, 100);

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


  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.


2 thoughts on “How to draw a wavy line in iOS app?

Leave a Reply

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

You are commenting using your 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 )

Google+ photo

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

Connecting to %s