How to draw a transparent line?

graphics2d, java, jpanel, line, transparency

Solution

The short answer is to set the `alpha` for the color of your graphic context:

float alpha = 0.5;
Color color = new Color(1, 0, 0, alpha); //Red 
g2.setPaint(color);

Alpha ranges between `0.0f` (invisible) to `1.0f` (opaque)

For the long answer with examples, see this article.

Problem

I am drawing a solid blue line on a JPanel via ``` public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; super.paint(g2); if (path.size() >= 2) { BasisStroke stroke = new BasicStroke(Config.TILE_SIZE_IN_PIXEL / 3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL); g2.setStroke(stroke); g2.setPaint(Color.BLUE); g2.setPaintMode(); for (int i = 0; i < path.size() - 1; i++) { g2.drawLine(path.get(i).x, path.get(i).y, path.get(i + 1).x, path.get(i + 1).y); } } } ``` Yet I want this line to be semi-transparent. How do I achieve that?

Original source

Related problems