Nxt*_*xt3 3 java javafx canvas
我正在编写一个(基本上)模仿 MS Paint 的应用程序;可以选择铅笔工具,画一条笔画为3的线;您可以选择标记工具并绘制一条笔划为 7 等的线。
我想在我的画布周围画一个边框。这很简单,是的。但是,使用我拥有的其他方法,我能想到的唯一实现方法是在绘制边界后进行大量抽查。是否有一种有效的方法可以在不与已选择工具的笔触/颜色冲突的情况下执行此操作?
这是drawBorder()方法:
private void drawBorder(GraphicsContext g) {
final double canvasWidth = g.getCanvas().getWidth();
final double canvasHeight = g.getCanvas().getHeight();
g.setStroke(Color.BLACK);
g.setLineWidth(4);
g.strokeRect(0, 0, canvasWidth, canvasHeight);
//sets the color back to the currently selected ColorPicker color
g.setStroke(selectedColor);
}
Run Code Online (Sandbox Code Playgroud)
但是,此代码将与我的clear()操作发生冲突
clearTool.setOnAction(e -> {
graphics.clearRect(0, 0,
canvas.getWidth(), canvas.getHeight());
drawBorder(graphics);
});
Run Code Online (Sandbox Code Playgroud)
因为在清除 Canvas 后,笔划线宽将为 4。这是一个问题,因为如果我将铅笔工具作为所选工具(笔划线宽为 3),它将为 4,直到我选择另一个工具并切换回来到铅笔工具;此外,如果我在按下清除按钮时选择了标记工具,同样的概念也适用(笔画线宽为 4,直到我选择另一个工具,然后重新选择标记工具)。
我试图避免必须为每个工具设置检查,并让它每次都重置笔划的线宽——虽然这可行,但似乎很复杂。
考虑将画布放在窗格中,并使用 CSS 来设置窗格的样式。例如:
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class CanvasWithBorderExample extends Application {
@Override
public void start(Stage primaryStage) {
final int SIZE = 400 ;
Canvas canvas = new Canvas(SIZE, SIZE);
GraphicsContext gc = canvas.getGraphicsContext2D() ;
gc.setStroke(Color.RED);
gc.moveTo(0, 0);
gc.lineTo(SIZE, SIZE);
gc.stroke();
StackPane canvasContainer = new StackPane(canvas);
canvasContainer.getStyleClass().add("canvas");
VBox root = new VBox(10, canvasContainer, new Button("Click here"));
root.setFillWidth(false);
VBox.setVgrow(canvasContainer, Priority.NEVER);
root.setAlignment(Pos.CENTER);
Scene scene = new Scene(root);
scene.getStylesheets().add("canvas-with-border.css");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Run Code Online (Sandbox Code Playgroud)
使用 canvas-with-border.css:
.canvas {
-fx-background-color: antiquewhite, white ;
-fx-background-insets: 0, 20 ;
-fx-padding: 20 ;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7363 次 |
| 最近记录: |