如何绘制透明线?

时间:2012-11-17 16:35:53

标签: java jpanel line transparency graphics2d

我正在通过

在JPanel上画一条蓝线
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);
        }
    }
}

但我希望这条线是半透明的。我如何实现这一目标?

1 个答案:

答案 0 :(得分:7)

简短的回答是为图形上下文的颜色设置alpha

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

Alpha范围介于0.0f(不可见)到1.0f(不透明)

之间

对于带有示例的长答案,see this article