如何在文本区域上绘图?

时间:2017-10-31 05:57:50

标签: java user-interface javafx layout-manager

我正在处理的程序只是在StackPane上使用画布层来描绘文本或图像。我想要实现的是当我释放鼠标MouseEvent.MOUSE_RELEASED处理程序时,它将自动获取画布的快照,将图像添加到ImageView Cover并将其显示在TextArea之上},但它无法将更改添加到类StackPane,即ImageView

我在这里有一个程序,我将添加到另一个我正在处理的程序中,我计划从主类TextCanvas中取出所有内容到主菜单控制器类中项目

主类TextCanvas.java:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelReader;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javax.imageio.ImageIO;

public class TextCanvas extends Application
{
    private ScrollPane Scroll = new ScrollPane();

    Canvas Can = new Canvas(800, 400);
    GraphicsContext GG = Can.getGraphicsContext2D();

    TextArea TA = new TextArea();

    ImageView Cover = new ImageView();

    VBox ButtonBox = new VBox();

    WordCanvas WC = new WordCanvas(Can, TA, GG);

    @Override
    public void start(Stage PrimaryStage)
    {
        ToggleGroup DrawErase = new ToggleGroup();

        ToggleButton Draw = new ToggleButton("Draw");
        ToggleButton Erase = new ToggleButton("Erase");
        Button Clear = new Button("Clear");
        Draw.setToggleGroup(DrawErase);
        Erase.setToggleGroup(DrawErase);

        double DotsPerInch = Screen.getPrimary().getDpi();
        double W = DotsPerInch * 8.5;
        double H = DotsPerInch * 11.0;

        StackPane Stack = new WordCanvas(W, H);

        WC.GetArea().setMaxWidth(W);
        WC.GetArea().setMaxHeight(H);
        WC.GetCan().setWidth(W);
        WC.GetCan().setHeight(H);

        DrawErase.selectedToggleProperty().addListener(new ChangeListener<Toggle>()
        {
            public void changed(ObservableValue<? extends Toggle> OV, Toggle TOld, Toggle TNew)
            {
                if(TNew == null)
                {
                    GG.setStroke(Color.TRANSPARENT);

                    Stack.getChildren().remove(WC.GetCan());
                }
                else if(DrawErase.getSelectedToggle().equals(Draw))
                {
                    GG.setStroke(Color.BLACK);

                    if(!Stack.getChildren().contains(WC.GetCan()))
                    {
                        Stack.getChildren().add(WC.GetCan());
                    }
                }
                else if(DrawErase.getSelectedToggle().equals(Erase))
                {
                    GG.setStroke(Color.WHITE);

                    if(!Stack.getChildren().contains(WC.GetCan()))
                    {
                        Stack.getChildren().add(WC.GetCan());
                    }
                }
            }
        });

        Clear.setOnAction(new EventHandler<ActionEvent>()
        {
            @Override
            public void handle(ActionEvent e)
            {
                WC.GetGC().clearRect(0, 0, W, H);

                Stack.getChildren().remove(WC.GetCover());
            }
        });

        Button Snap = new Button("Snap");

        Snap.setOnAction(new EventHandler<ActionEvent>()
        {
            @Override
            public void handle(ActionEvent e)
            {
                Cover.setMouseTransparent(true);

                WritableImage WImage = Can.snapshot(new SnapshotParameters(), null);

                ByteArrayOutputStream Bos = new ByteArrayOutputStream();

                try
                {
                    ImageIO.write(SwingFXUtils.fromFXImage(WImage, null), "png", Bos);
                }
                catch(IOException ex)
                {
                    Logger.getLogger(WordCanvas.class.getName()).log(Level.SEVERE, null, ex);
                }

                InputStream Fis = new ByteArrayInputStream(Bos.toByteArray());
                Image Imos = new Image(Fis);

                int IW = (int) Imos.getWidth();
                int IH = (int) Imos.getHeight();

                WritableImage OutputImage = new WritableImage(IW, IH);
                PixelReader PReader = Imos.getPixelReader();
                PixelWriter PWriter = OutputImage.getPixelWriter();

                for (int y = 0; y < IH; y++)
                {
                    for (int x = 0; x < IW; x++)
                    {
                        int argb = PReader.getArgb(x, y);

                        int r = (argb >> 16) & 0xFF;
                        int g = (argb >> 8) & 0xFF;
                        int b = argb & 0xFF;

                        if(r >= 0xCF && g >= 0xCF && b >= 0xCF)
                        {
                            argb &= 0x00FFFFFF;
                        }

                        PWriter.setArgb(x, y, argb);
                    }
                }

                if(!Stack.getChildren().contains(WC.GetCover()))
                {
                    WC.GetCover().setImage(OutputImage);

                    Stack.getChildren().add(WC.GetCover());
                }
                else
                {
                    WC.GetCover().setImage(OutputImage);
                }
            }
        });

        ButtonBox.getChildren().addAll(Draw, Erase, Clear, Snap);

        BorderPane Border = new BorderPane();
        Border.setCenter(Stack);
        Border.setBottom(ButtonBox);

        Scroll.setContent(Border);
        Scroll.setFitToWidth(true);
        Scroll.setFitToHeight(true);

        Scene MainScene = new Scene(Scroll);

        PrimaryStage.setMaximized(true);
        PrimaryStage.setTitle("Practice Canvas");
        PrimaryStage.setScene(MainScene);
        PrimaryStage.show();
    }

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

包含TextArea和Canvas的辅助类:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Cursor;
import javafx.scene.SnapshotParameters;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.TextArea;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelReader;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javax.imageio.ImageIO;

public class WordCanvas extends StackPane
{
    private Canvas Can = new Canvas();

    private GraphicsContext GC = Can.getGraphicsContext2D();

    private TextArea Area = new TextArea();

    private ImageView Cover = new ImageView();

    double Width;
    double Height;

    public WordCanvas()
    {
        CreateUI();
    }

    public WordCanvas(double W, double H)
    {
        this.Width = W;
        this.Height = H;

        CreateUI();
    }

    public WordCanvas(ImageView IV)
    {
        this.Cover = IV;
    }

    public WordCanvas(Canvas C, TextArea TA, GraphicsContext GG)
    {
        this.Can = C;
        this.Area = TA;
        this.GC = GG;

        CreateUI();
    }

    public void CreateUI()
    {
        Caligraphy();

        Imagination();

        Color C = Color.STEELBLUE;

        BackgroundFill BFill = new BackgroundFill(C, CornerRadii.EMPTY, Insets.EMPTY);

        Background BGround = new Background(BFill);

        this.getChildren().addAll(Area);

        this.setBackground(BGround);
    }

    public void Caligraphy()
    {
        Area.setMaxWidth(Width);
        Area.setMaxHeight(Height);
    }

    public void Imagination()
    { 
        double CanvasWidth = GC.getCanvas().getWidth();
        double CanvasHeight = GC.getCanvas().getHeight();

        GC.setFill(Color.TRANSPARENT);
        GC.fillRect(0, 0, Can.getWidth(), Can.getHeight());
        GC.rect(0, 0, CanvasWidth, CanvasHeight);
        GC.setLineWidth(3);

        Can.addEventHandler(MouseEvent.MOUSE_ENTERED, new EventHandler<MouseEvent>()
        {
            @Override
            public void handle(MouseEvent event)
            {
                Can.setCursor(Cursor.CROSSHAIR);
            }
        });

        Can.addEventHandler(MouseEvent.MOUSE_EXITED, new EventHandler<MouseEvent>()
        {
            @Override
            public void handle(MouseEvent event)
            {
                Can.setCursor(Cursor.DEFAULT);
            }
        });

        Can.addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>()
        {
            @Override
            public void handle(MouseEvent event)
            {
                GC.beginPath();
                GC.lineTo(event.getX(), event.getY());
                GC.moveTo(event.getX(), event.getY());
                GC.stroke();
            }
        });

        Can.addEventHandler(MouseEvent.MOUSE_DRAGGED, new EventHandler<MouseEvent>()
        {
            @Override
            public void handle(MouseEvent event)
            {
                GC.lineTo(event.getX(), event.getY());
                GC.stroke();
            }
        });

        Can.addEventHandler(MouseEvent.MOUSE_RELEASED, new EventHandler<MouseEvent>()
        {
            @Override
            public void handle(MouseEvent event)
            {
                ImageView IV = new ImageView();

                WordCanvas Stack = new WordCanvas(IV);

                Cover.setMouseTransparent(true);

                WritableImage WImage = Can.snapshot(new SnapshotParameters(), null);

                ByteArrayOutputStream Bos = new ByteArrayOutputStream();

                try
                {
                    ImageIO.write(SwingFXUtils.fromFXImage(WImage, null), "png", Bos);
                }
                catch(IOException ex)
                {
                    Logger.getLogger(WordCanvas.class.getName()).log(Level.SEVERE, null, ex);
                }

                InputStream Fis = new ByteArrayInputStream(Bos.toByteArray());
                Image Imos = new Image(Fis);

                int IW = (int) Imos.getWidth();
                int IH = (int) Imos.getHeight();

                WritableImage OutputImage = new WritableImage(IW, IH);
                PixelReader PReader = Imos.getPixelReader();
                PixelWriter PWriter = OutputImage.getPixelWriter();

                for (int y = 0; y < IH; y++)
                {
                    for (int x = 0; x < IW; x++)
                    {
                        int argb = PReader.getArgb(x, y);

                        int r = (argb >> 16) & 0xFF;
                        int g = (argb >> 8) & 0xFF;
                        int b = argb & 0xFF;

                        if(r >= 0xCF && g >= 0xCF && b >= 0xCF)
                        {
                            argb &= 0x00FFFFFF;
                        }

                        PWriter.setArgb(x, y, argb);
                    }
                }

                if(!Stack.getChildren().contains(Cover))
                {
                    Cover.setImage(OutputImage);

                    Stack.getChildren().add(Cover);
                }
                else
                {
                    Cover.setImage(OutputImage);
                }
            }
        });
    }

    public void SetCan(Canvas C)
    {
        this.Can = C;
    }

    public Canvas GetCan()
    {
        return Can;
    }

    public void SetGC(GraphicsContext GG)
    {
        this.GC = GG;
    }

    public GraphicsContext GetGC()
    {
        return GC;
    }

    public void SetArea(TextArea TA)
    {
        this.Area = TA;
    }

    public TextArea GetArea()
    {
        return Area;
    }

    public ImageView GetCover()
    {
        return Cover;
    }
}

在主类中,Snap按钮处理程序确实可以正常工作,但我想要的是,在辅助类中,MouseEvent.MOUSE_RELEASED偶数处理程序会自动创建快照并执行主类中的Snap按钮确实。然而,我尝试过的任何作品都没有用,它甚至不接受this.getChildren().add(Cover)

另一个小问题,我希望WritableImage能够通过更优雅的解决方案自动变得透明。用户@jewelsea提供了一个完美的解决方案here,但我更喜欢一些不需要读取每个像素的东西。现有的png文件可以按预期工作,但是当我创建自己的png文件时,它们不是透明的。

1 个答案:

答案 0 :(得分:0)

目前尚不清楚为什么要在每次抽奖中创建画布,与父母的孩子一起玩,以及为什么每次都需要捕捉屏幕并创建图像。

您只想绘制文本区域,因此在其上绘制一个画布。画布的mouseTransparentProperty可用于决定哪个图层获得输入。

public class TextCanvas extends Application {

    private GraphicsContext gc;

    @Override
    public void start(Stage primaryStage) {
        TextArea textArea = new TextArea();
        Canvas canvas = createCanvas();

        ToggleButton draw = new ToggleButton("Draw");
        ToggleButton erase = new ToggleButton("Erase");
        ToggleGroup drawErase = new ToggleGroup();
        draw.setToggleGroup(drawErase);
        erase.setToggleGroup(drawErase);
        drawErase.selectedToggleProperty().addListener((ov, oldV, newV) -> {
            if (newV == null) {
                gc.setStroke(Color.TRANSPARENT);
                canvas.setMouseTransparent(true);
            } else if (drawErase.getSelectedToggle().equals(draw)) {
                System.out.println("Fd");
                gc.setStroke(Color.BLACK);
                canvas.setMouseTransparent(false);
            } else if (drawErase.getSelectedToggle().equals(erase)) {
                gc.setStroke(Color.WHITE);
                canvas.setMouseTransparent(false);
            }
        });

        Button clear = new Button("Clear");
        clear.setOnAction(e -> gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight()));

        CheckBox cb = new CheckBox("Show canvas");
        cb.setSelected(true);
        canvas.visibleProperty().bind(cb.selectedProperty());

        VBox buttonBox = new VBox(draw, erase, clear, cb);

        StackPane stack = new StackPane(textArea, canvas);
        ScrollPane scrollPane = new ScrollPane(stack);
        scrollPane.setFitToHeight(true);

        canvas.widthProperty().bind(scrollPane.widthProperty());
        canvas.heightProperty().bind(scrollPane.heightProperty());

        stack.setBackground(new Background(new BackgroundFill(Color.STEELBLUE, CornerRadii.EMPTY, Insets.EMPTY)));

        BorderPane border = new BorderPane();
        border.setCenter(scrollPane);
        border.setBottom(buttonBox);

        primaryStage.setMaximized(true);
        primaryStage.setTitle("Practice Canvas");
        primaryStage.setScene(new Scene(border));
        primaryStage.show();
    }

    private Canvas createCanvas() {
        Canvas canvas = new Canvas();
        gc = canvas.getGraphicsContext2D();
        gc.setLineWidth(3);

        canvas.setOnMouseEntered(event -> canvas.setCursor(Cursor.CROSSHAIR));
        canvas.setOnMouseExited(event -> canvas.setCursor(Cursor.DEFAULT));

        canvas.setOnMousePressed(event -> {
            gc.beginPath();
            gc.lineTo(event.getX(), event.getY());
            gc.moveTo(event.getX(), event.getY());
            gc.stroke();
        });
        canvas.setOnMouseDragged(event -> {
            gc.lineTo(event.getX(), event.getY());
            gc.stroke();
        });

        canvas.setMouseTransparent(true);
        return canvas;
    }

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

修改:我添加了一个复选框以切换画布的可见性。您必须清除每个用户操作对每种模式执行的操作的使用要求。在任何情况下,这应该足以使用。

此外,使用适当的Java命名约定:局部变量,(非常量)字段名称和方法参数应以小写字母开头。