假设我有一些形状,比如:
Shape s1 = new Rectangle(10, 10);
Shape s2 = new Circle(10);
等等,您想在画布上绘制它们。在Swing中,可以通过Graphics2D.draw(Shape shape)方法实现,但我在JavaFX GraphicsContext中没有看到相应的方法。在JavaFX中是否有类似的方法呢?
我不确定直接在画布上绘制对象是否可行,但可以直接在舞台节点上绘制,例如这个例子:
package javafx8_shape;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
/**
*
* @web java-buddy.blogspot.com
*/
public class JavaFX8_Shape extends Application {
@Override
public void start(Stage primaryStage) {
Group root = new Group();
Scene scene = new Scene(root, 500, 500, Color.BLACK);
//Filled rectangle
Rectangle rect1 = new Rectangle(10, 10, 200, 200);
rect1.setFill(Color.BLUE);
//Transparent rectangle with Stroke
Rectangle rect2 = new Rectangle(60, 60, 200, 200);
rect2.setFill(Color.TRANSPARENT);
rect2.setStroke(Color.RED);
rect2.setStrokeWidth(10);
//Rectangle with Stroke, no Fill color specified
Rectangle rect3 = new Rectangle(110, 110, 200, 200);
rect3.setStroke(Color.GREEN);
rect3.setStrokeWidth(10);
root.getChildren().addAll(rect1, rect2, rect3);
primaryStage.setTitle("java-buddy.blogspot.com");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
然而,Canvas API 通常是通过方法调用绘制形状、矩形等的方式。因此,简要概括一下,您甚至可以将矩形对象绘制到其他节点上,比如一个 HBOX:
HBox root = new HBox(rectangle);
gc.setFill(Color.WHITESMOKE);
gc.fillRect(gc.getCanvas().getLayoutX(),
gc.getCanvas().getLayoutY(),
gc.getCanvas().getWidth(),
gc.getCanvas().getHeight());
gc.setFill(Color.GREEN);
gc.setStroke(Color.BLUE);
private void drawRectangle(GraphicsContext gc,Rectangle rect){
gc.setFill(Color.WHITESMOKE);
gc.fillRect(rect.getX(),
rect.getY(),
rect.getWidth(),
rect.getHeight());
gc.setFill(Color.GREEN);
gc.setStroke(Color.BLUE);
}
return gc;
。 - bugybunny