سؤال

How can I get the line coordinates after applying graphics2d transformation? Here is the code:

double startX = 100;
double startY = 100;
double endX   = 500;
double endY   = 500;

AffineTransform rotation = new AffineTransform();      
double angle = Math.toRadians(90);
rotation.rotate(angle, 200, 200); 

Graphics2D brush = (Graphics2D) g;
Line2D.Double line = new Line2D.Double(startX, startY, endX, endY);  
brush.setTransform(rotation);
brush.draw(line);
هل كانت مفيدة؟

المحلول

I dont see any "great" way of doing this but heres what I got. You can use a PathIterator object to get the result of the line after the rotation is applied. From there you can loop through the coordinates inside the PathIterator and get your x and y coordinates.

Heres an awnser that has a cleaner way of grabbing out the coordinates if your interested iterate through each point on a line/path in java

Also if you plan to use this in any sort of graphics I would not recommend doing this process inside your paint method.

double startX = 100;
double startY = 100;
double endX   = 500;
double endY   = 500;

AffineTransform rotation = new AffineTransform();      
double angle = Math.toRadians(90);
rotation.rotate(angle, 200, 200); 

Line2D.Double line = new Line2D.Double(startX, startY, endX, endY);
PathIterator it = line.getPathIterator(rotation);
while(!it.isDone()) {
    double [] values = new double[6];
    it.currentSegment(values);
    System.out.println("["+values[0] + ", " + values[1] + "]");
    it.next();
}

Also I noticed some comments about using a Paths instead of your inital line. I agree that a path should be used whenever you need to be applying transforms for a "shape" due to their built in methods for handling it. Heres an example of using a path instead of your Line2D

double startX = 100;
double startY = 100;
double endX   = 500;
double endY   = 500;

AffineTransform rotation = new AffineTransform();      
double angle = Math.toRadians(90);
rotation.rotate(angle, 200, 200); 

Path2D path = new Path2D.Double();
path.moveTo(startX, startY);
path.lineTo(endX, endY);

path.transform(rotation);

double [] values = new double[6];
for(PathIterator it = path.getPathIterator(null); !it.isDone();) {
    it.currentSegment(values);
    System.out.println("["+values[0] + ", " + values[1] + "]");
    it.next();
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top