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

21

我想在我的应用程序中绘制一个红色矩形,但我需要让它有点透明,以便下面的组件仍然可见。然而,我仍希望一些颜色仍然可见。我正在使用以下方法进行绘制:

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

有谁知道如何使红色阴影稍微透明一些?但我不需要完全透明。

2个回答

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

请参见使用4个参数(int或float类型)的Color构造函数以获取更多详细信息。


2
尝试这个:(但它只适用于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); 
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接