RSS

Plotting a Sine Wave with the iPhone SDK

April 17th, 2008 Posted in Software Development, iPhone

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

[del.icio.us] [Digg] [Reddit] [Technorati]

RSS feed | Trackback URI

2 Comments »

Comment by Leo
2008-04-18 16:29:10

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….

 
Comment by Leo
2008-04-18 16:40:03

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);

 
Name (required)
E-mail (required - never shown publicly)
URI
Subscribe to comments via email
Your Comment (smaller size | larger size)
You may use <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> in your comment.