tags:

views:

52

answers:

2

I'm looking for an efficient way to convert axes coordinates to pixel coordinates for multiple screen resolutions.

For example if had a data set of values for temperature over time, something like:

int temps[] = {-8, -5, -4, 0, 1, 0, 3};
int times[] = {0, 12, 16, 30, 42, 50, 57};

What's the most efficient way to transform the dataset to pixel coordinates so I could draw a graph on a 800x600 screen.

+1  A: 

Assuming you're going from TEMP_MIN to TEMP_MAX, just do:

y[i] = (int)((float)(temps[i] - TEMP_MIN) * ((float)Y_MAX / (float)(TEMP_MAX - TEMP_MIN)));

where #define Y_MAX (600). Similarly for the x-coordinate. This isn't tested, so you may need to modify it slightly to deal with the edge-case (temps[i] == TEMP_MAX) properly.

Oli Charlesworth
...but the example has temperatures below 0...
caf
@caf: Good point; modifying answer now...
Oli Charlesworth
+1  A: 

You first need to determine the maximum and minimum values along each axis. Then you can do:

x_coord[i] = (x_val[i] - x_max) * X_RES / (x_max - x_min);

...and the same for Y. (Although you will probably want to invert the Y axis).

caf
You'll probably need to do this in floating-point to achieve the correct accuracy (as in my answer), and to avoid overflow issues.
Oli Charlesworth
@Oli: Yep, that can be achieved by making `X_RES` a floating point constant like `800.0`.
caf