如何在透明颜色的图形中制作矩形?

我正在尝试在我的应用程序上用红色阴影绘制一个矩形,但我需要使它变得透明,以便它下面的组件仍然显示。但是,我仍然希望仍然显示一些颜色。我绘制的方法如下:

protected void paintComponent(Graphics g) {
    if (point != null) {
        int value = this.chooseColour(); // used to return how bright the red is needed

        if(value !=0){
            Color myColour = new Color(255, value,value );
            g.setColor(myColour);
            g.fillRect(point.x, point.y, this.width, this.height);
        }
        else{
            Color myColour = new Color(value, 0,0 );
            g.setColor(myColour);
            g.fillRect(point.x, point.y, this.width, this.height);
        }
    }
}

有谁知道我怎样才能使红色阴影有点透明?我不需要它完全透明。


答案 1
int alpha = 127; // 50% transparent
Color myColour = new Color(255, value, value, alpha);

有关更多详细信息,请参阅采用 4 个参数(任一参数或 )的 Color 构造函数intfloat


答案 2

试试这个:(但它适用于Graphics2D objeccts,不适用于Graphics)

protected void paintComponent(Graphics2D g) {
    if (point != null) {
        int value = this.chooseColour(); // used to return how bright the red is needed
        g.setComposite(AlphaComposite.SrcOver.derive(0.8f));

        if(value !=0){
            Color myColour = new Color(255, value,value );
            g.setColor(myColour);
            g.fillRect(point.x, point.y, this.width, this.height);
        }
        else{
            Color myColour = new Color(value, 0,0 );
            g.setColor(myColour);
            g.fillRect(point.x, point.y, this.width, this.height);
        }

        g.setComposite(AlphaComposite.SrcOver); 
    }
}