I have drawn a straight line in a canvas and filled with a solid color. I want to border this straight line with a black colored border.
Asked
Active
Viewed 1.1k times
2 Answers
4
You can use two fillRect with different size and color
example:
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);

Mailkov
- 1,231
- 1
- 13
- 17
-
What if it has an amoeba shape. Can't I get some shape property to draw the border. – Shantanu Chandra Dec 09 '14 at 11:35
-
in GraphicContext thereisn't a border function – Mailkov Dec 09 '14 at 11:39
-
If this answer helped you ... you can set as correct or upvote this – Mailkov Dec 09 '14 at 11:57
3
In addition to filling your shape, also specify a stroke on the graphics context and ask it to stroke the shape.
Here is an example (adapted from the Oracle Canvas tutorial):
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); }
}
There is more information on the canvas drawing API in the GraphicsContext JavaDoc.

jewelsea
- 150,031
- 14
- 366
- 406