Skip to content
Advertisement

How to draw polyline with negative coordinates in java [closed]

I want to draw polyline with positive and negative coordinates.

e.g.
125,66
126,62
-128,59
-127,55
-125,51
-124,47
-122,43
-121,40
-119,38
-118,36
These are the sample coordinate to draw the polyline in Jframe.
After drawing the polyline it will show the line for positive coordinates only.

int j =0;
System.out.println(imageByteArray.length);
int[] x = new int [imageByteArray.length/2];
int[] y = new int [imageByteArray.length/2];
for (int i = 0; i <= imageByteArray.length-1;) 
{
    System.out.println(imageByteArray[i] +","+imageByteArray[i+1]);
    int s1 = imageByteArray[i];
    int s2 = imageByteArray[i+1];
    
    j++;
    i = i+2;
    
}

gp.drawPolyline( x, y, j );

Please help me to understand how we can draw polyline with such coordinates using java technology.

Advertisement

Answer

Let’s say your drawing panel (JPanel) is 400 x 400 pixels.

Let’s take your polyline. I’m assuming these are x, y coordinates.

 125, 66
 126, 62
-128, 59
-127, 55
-125, 51
-124, 47
-122, 43
-121, 40
-119, 38
-118, 36

The y coordinates range from 36 to 66. These coordinates fit easily in the 0 to 399 range of our drawing panel.

The x coordinates range from -128 to 126. These coordinates don’t fit in the 0 to 399 range of our drawing panel.

The absolute difference between the minimum and the maximum x value is 254. 254 is less than the 400 pixels we have to work with.

Therefore, by adding 128 to each x coordinate, we can translate the polyline into something that can be drawn on our 400 x 400 drawing panel.

Advertisement