This discussion is archived
1 Reply Latest reply: Mar 1, 2013 5:49 AM by James_D RSS

graphics context rotate

kapac Newbie
Currently Being Moderated
Hi;
i made a rectangle with graphicscontext gc on a canvas
How to rotate it using gc.rotate().i tried without result!
help please
regards
  • 1. Re: graphics context rotate
    James_D Guru
    Currently Being Moderated
    Drawing on a canvas is a one-shot operation. So you can't move shapes around within the canvas after drawing them. You can, however, rotate the entire canvas.

    This simple example shows what's happening. You can make it look "better" (rather than "instructive") by setting the background of the scene to a background color and filling the entire canvas with Color.TRANSPARENT.
    import javafx.application.Application;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.scene.Scene;
    import javafx.scene.canvas.Canvas;
    import javafx.scene.canvas.GraphicsContext;
    import javafx.scene.control.Button;
    import javafx.scene.layout.BorderPane;
    import javafx.scene.paint.Color;
    import javafx.stage.Stage;
    
    public class CanvasRotateTest extends Application {
    
         @Override
         public void start(Stage primaryStage) {
              final Canvas canvas = new Canvas(400, 400);
              final GraphicsContext gc = canvas.getGraphicsContext2D();
              gc.setFill(Color.ANTIQUEWHITE);
              gc.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
              gc.setFill(Color.SALMON);
              gc.fillRect(50, 50, 200, 100);
              final BorderPane root = new BorderPane();
              root.setCenter(canvas);
              
              final Button rotateButton = new Button("Rotate");
              rotateButton.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                  canvas.setRotate(canvas.getRotate()+45);
                }
              });
              
              root.setBottom(rotateButton);
              
              Scene scene = new Scene(root);
              primaryStage.setScene(scene);
              primaryStage.show();
         }
    
         public static void main(String[] args) {
              launch(args);
         }
    }
    Update:
    I didn't read your post carefully enough. The gc.rotate(...) method will apply a rotation to any input subsequently sent to the graphics context. So if you were to call gc.rotate(45) before drawing the rectangle, the rectangle would appear rotated by 45 degrees. However, it will not change anything already drawn.

    Edited by: James_D on Mar 1, 2013 5:47 AM

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points