繁体   English   中英

drawImage()后画布是空白的

[英]canvas is blank after drawImage()

我有一个绘图窗口,允许用户打开图像,在上面绘图,然后保存。

我在画布上有它,我可以创建一个空白画布,在上面画画,并保存它没有任何问题。 但是当我尝试打开该图像并执行以下操作时:

GraphicsContext gc = canvas.getGraphicsContext2D();
File file = new File(path);
Image img = new Image(file.toURI().toString());
gc.drawImage(img,0,0);

它和以前一样。 我得到一张空白画布,那张图片永远不会出现。

我在代码中做错了吗? 我知道路径是正确的,因为我可以在程序的其他部分的缩略图中看到该图像。

UPDATE

这是一个完整的示例程序

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class GUITest extends Application{

    String path = "10-9-2016-22-28.png";

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

    @Override
    public void start(Stage primaryStage) throws Exception {
        Pane root = new Pane();
        Canvas canvas = new Canvas(600,800);

        GraphicsContext gc = canvas.getGraphicsContext2D();
        Image original = new Image(getClass().getResourceAsStream(path));
        gc.drawImage(original, 0, 0);

        root.getChildren().add(canvas);
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

它现在可以工作,直到我执行canvas.widthProperty().bind(root.widthProperty()); canvas.heightProperty().bind(root.heightProperty()); 将画布尺寸与其父级的尺寸绑定是否有问题?

执行第一个布局过程时, Pane的大小变为非0。 在大小为(0, 0) 由于画布中没有大小(0, 0)的空间,因此删除了所有内容。 稍后当Canvas增长到root的大小时,您不会重绘图像,因此不会显示任何内容。

因此,每次调整Canvas大小时,您需要再次绘制画布内容(或者至少直到大小变为非零)。

出于同样的原因,您需要在根元素处设置场景的首选大小,而不是通过设置“ Canvas大小。

@Override
public void start(Stage primaryStage) throws Exception {
    Pane root = new Pane();
    root.setPrefSize(600, 800);
    Canvas canvas = new Canvas();

    GraphicsContext gc = canvas.getGraphicsContext2D();
    Image original = new Image(getClass().getResourceAsStream(path));

    root.layoutBoundsProperty().addListener((observable, oldValue, newValue) -> {
        canvas.setWidth(newValue.getWidth());
        canvas.setHeight(newValue.getHeight());
        gc.drawImage(original, 0, 0);
    });

    root.getChildren().add(canvas);
    Scene scene = new Scene(root);
    primaryStage.setScene(scene);
    primaryStage.show();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM