k0pernikus
k0pernikus

Reputation: 66500

How to draw a transparent line?

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?

Upvotes: 3

Views: 5633

Answers (1)

sampson-chen
sampson-chen

Reputation: 47267

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.

Upvotes: 8

Related Questions