Tom Rogati
Tom Rogati

Reputation: 21

drawing a shape over an image and rotating it in java

Hi I am drawing a shape over an image. The shape basically contains a couple of connected lines. I now need to rotate the drawn shape but not the background image. The code that i have so far is:

public void drawTrack(){
    try {

        File input = new File(mapPath);
        md.image = ImageIO.read(input);
    } catch (IOException ie) {
        System.out.println("Error:"+ie.getMessage());
    }

    Graphics2D g2d = md.image.createGraphics();
    g2d.setColor(Color.RED);
    BasicStroke bs = new BasicStroke(2);
    g2d.setStroke(bs);


    int currentX = Integer.parseInt(ts.xcord.getText());
    int currentY = Integer.parseInt(ts.ycord.getText());
    int scale = Integer.parseInt(ts.size.getText());
    td.computeTracksMotion(currentX, currentY, scale);

    for(TracksMotion currentTm: td.tm){
    // drawing the lines    g2d.drawLine(currentTm.oldX,currentTm.oldY,currentTm.newX,currentTm.newY);
    }

    md.repaint();
}

Could you let me know what I should do.

Upvotes: 2

Views: 752

Answers (2)

trashgod
trashgod

Reputation: 205865

One way to rotate a Shape without affecting the background is to use the createTransformedShape() method of AffineTransform, as seen in this example.

Upvotes: 1

stacker
stacker

Reputation: 68982

You could explore the Java2D API and use the translate and rotate methods from Graphics2D.

An example you find here.

  AffineTransform rat = new AffineTransform();
  rat.setToTranslation(100, 0);
  rat.rotate(Math.PI / 6);
  g2.transform(rat);

Please note that the angle is provided in radians.

Upvotes: 1

Related Questions