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



我想在我的应用程序上画一个红色阴影的矩形,但我需要使它透明,这样它下面的组件仍然会显示。但是我仍然希望一些颜色仍然可以显示出来。我绘制的方法如下:

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);
        }
    }
}

有谁知道我怎么能使红色阴影有点透明吗?我不需要完全透明

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

请参阅Color构造函数,该构造函数接受4个参数(intfloat)以了解更多详细信息。

试试这个(但它将适用于Graphics2D对象而不是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); 
    }
}

最新更新