Plotting a Sine Wave with the iPhone SDK

Graphics Icon
Got the following request from Leo on the Exploring iPhone Graphics Part 1 article:

Could you give me a quick primer on how to draw a sinus curve (or similar curve) with the data coming from an array?







Here it is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#define PI 3.14159
 
CGContextBeginPath(ctx);
 
int x;
for(int y=rect.origin.y; y < rect.size.height; y++)
{
    x = ((rect.size.width/4) * sin(((y*4) % 360) * PI/180)) + rect.size.width/2;
 
    if(y == 0)
    {
        CGContextMoveToPoint(ctx, x, y);
    }
    else
    {
        CGContextAddLineToPoint(ctx, x, y);
    }
}
 
CGContextStrokePath(ctx);

The CGContextBeginPath function starts a graphics path. Next we loop the y screen coordinate from the top of the screen to the bottom of the screen. For each y position we calculate the x position based on the sin function. The wave will be half the width of the screen and centered. On the first iteration of the loop (y = 0) we use the CGContextMoveToPoint to set the first drawing position. On each subsequent iteration we draw a line from the last point to the current point.

Here’s a screen shot with this code added to the original application:
Sine wave screenshots

Share and Enjoy:
  • StumbleUpon
  • Digg
  • Reddit
  • del.icio.us
  • Suggest to Techmeme via Twitter
  • Technorati
  • Slashdot
  • HackerNews
  • Twitter
  • Facebook
  • Print
You can leave a response, or trackback from your own site.

3 Responses to “Plotting a Sine Wave with the iPhone SDK”

  1. Leo says:

    I have this exact code in my test app:

    #define PI 3.14159
    - (void)drawRect:(CGRect)rect
    {
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextClearRect(ctx, rect);
    CGContextBeginPath(ctx);

    int x;
    for(int y=rect.origin.y; y < rect.size.height; y++)
    {
    x = ((rect.size.width/4) * sin(((y*4) % 360) * PI/180)) + rect.size.width/2;

    if(y == 0)
    {
    CGContextMoveToPoint(ctx, x, y);
    }
    else
    {
    CGContextAddLineToPoint(ctx, x, y);
    }
    }
    CGContextStrokePath(ctx);
    }

    and nothing happens! Either I forgot something – or you did….

  2. Leo says:

    We forgot to add ink to our pen… I added this line and it works as advertised!

    CGContextSetRGBStrokeColor(ctx, 1.0, 0.0, 1.0, 1.0);

  3. rok says:

    Hello.

    Nice snippet. I’d just like to add that you get much smoother curve if you change int x and int y to CGFloat x and CGFloat y.

    All best,

    Rok

Leave a Reply

*