移动形状JavaFX中的画布

移动形状JavaFX中的画布

本文介绍了移动形状JavaFX中的画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以使用GraphicsContext画布来创建一个圆形(或GraphicsContext创建的任何形状),然后移动它在画布上。如果是,什么是算法,这样做?我已经习惯了与Java工作,我只是无法弄清楚。

I would like to know if it's possible to use the GraphicsContext of a Canvas to create a circle(or any shape created with GraphicsContext) and then move it around on the canvas. If it is, what's the algorithm for doing so? I'm used to working with Java and I just can't figure it out.

感谢您事先的任何帮助。

Thanks in advance for any help.

推荐答案

基本上,这种工作方式是,你设置一个的和更新的形状基于一些的的。然后,在你画你的画布。

Basically, the way this works is that you setup a Canvas and update the location of the shape based on some Timeline. Then, in an AnimationTimer you paint your canvas.

import javafx.animation.*;
import javafx.application.Application;
import javafx.beans.property.*;
import javafx.scene.*;
import javafx.scene.canvas.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Duration;

public class AnimatedCircleOnCanvas extends Application {
    public static final double W = 200; // canvas dimensions.
    public static final double H = 200;

    public static final double D = 20;  // diameter.

    @Override public void start(Stage stage) {
        DoubleProperty x  = new SimpleDoubleProperty();
        DoubleProperty y  = new SimpleDoubleProperty();

        Timeline timeline = new Timeline(
            new KeyFrame(Duration.seconds(0),
                    new KeyValue(x, 0),
                    new KeyValue(y, 0)
            ),
            new KeyFrame(Duration.seconds(3),
                    new KeyValue(x, W - D),
                    new KeyValue(y, H - D)
            )
        );
        timeline.setAutoReverse(true);
        timeline.setCycleCount(Timeline.INDEFINITE);

        final Canvas canvas = new Canvas(W, H);
        AnimationTimer timer = new AnimationTimer() {
            @Override
            public void handle(long now) {
                GraphicsContext gc = canvas.getGraphicsContext2D();
                gc.setFill(Color.CORNSILK);
                gc.fillRect(0, 0, W, H);
                gc.setFill(Color.FORESTGREEN);
                gc.fillOval(
                    x.doubleValue(),
                    y.doubleValue(),
                    D,
                    D
                );
            }
        };

        stage.setScene(
            new Scene(
                new Group(
                    canvas
                )
            )
        );
        stage.show();

        timer.start();
        timeline.play();
    }

    public static void main(String[] args) { launch(args); }
}

这不过是简单的不使用画布,而是使用包含在一个TranslateTransition.

这篇关于移动形状JavaFX中的画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 11:42