使用JavaFx在画布中绘制形状周围的边框

时间:2014-12-09 08:38:23

标签: javafx border java-canvas

我在画布上画了一条直线,并用纯色填充。我想把这条直线与黑色边框接壤。

2 个答案:

答案 0 :(得分:3)

您可以使用两个不同大小和颜色的fillRect

示例:

final Canvas canvas = new Canvas(250,250);
GraphicsContext gc = canvas.getGraphicsContext2D();

gc.setFill(Color.BLUE);
gc.fillRect(0,0,100,20);
gc.setFill(Color.RED);
gc.fillRect(1,1,98,18);

答案 1 :(得分:2)

除了填充形状外,还要在图形上下文中指定笔划,并要求它描边形状。

以下是一个示例(改编自Oracle Canvas tutorial):

strokedshape

import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.canvas.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class CanvasStrokeDemo extends Application {
    @Override public void start(Stage stage) throws Exception {
        final Canvas canvas = new Canvas(250, 250);
        GraphicsContext gc = canvas.getGraphicsContext2D();

        // load the graphics context up with instructions to draw a shape.
        drawDShape(gc);

        // fill the shape.
        gc.setFill(Color.BLUE);
        gc.fill();

        // stroke an outline (border) around the shape.
        gc.setStroke(Color.GREEN);
        gc.setLineWidth(10);
        gc.stroke();

        stage.setScene(new Scene(new Group(canvas), Color.WHITE));    
        stage.show();
    }

    private void drawDShape(GraphicsContext gc) {
        gc.beginPath();
        gc.moveTo(50, 50);
        gc.bezierCurveTo(150, 20, 150, 150, 75, 150);
        gc.closePath();
    }

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

有关GraphicsContext JavaDoc中的画布绘制API的更多信息。

相关问题