tags:

views:

82

answers:

1

I want to draw an array of X and Y integers to a panel in a Java frame.

What is the best way to draw the line (currently I'm using Graphic's drawPolyline)?

How can I efficiently scale the integer values so they all fit in the panel area without knowing the max (Y) value?

Update, for example

public void paint(Graphics g)
{
  int height = panel.getHeight();
  int width = panel.getWidth();
  int[] xPoints = { ... values ... };
  int[] yPoints = { ... values ... };
  int nPoints = dataLength;
  // Scale xPoints and yPoints so they fit in the area of width and height
  // and draw line
  g.drawPolyline(xPoints, yPoints, nPoints);
  g.dispose();
}
+2  A: 

Without knowing both the x and y maximum values, I don't think this can be done, since you can't then calculate the scale needed. But if you have an array of points, then you can certainly search it to find the minimum and maximum x and y values.

If you have a means of getting the maximum values, read on (and for the benefit of others with a similar problem).

Find the maximum difference between any two x values between any two y values; call them max(dx) and max(dy) - these are max(x)-min(x) and max(y)-min(y) respectively.

Take the greater of width/max(dx) and height/max(dy). That number provides your scale; just modify every x value using ((x-min(x))/scale) and each y value using ((y-min(y))/scale)

You should now have the largest shape that will fit oriented relative 0,0.

Note: I have have negative coordinates, you will have to adjust them into the positive coordinate range before applying these formulas.

Software Monkey