2011-11-13 143 views
19

我试图在我的应用程序中以红色阴影画一个矩形,但我需要使其具有透明度,以便它下面的组件仍然可以显示。但是我仍然希望某些颜色仍然会显示。我正在绘制的方法如下:如何在透明颜色的图形中制作矩形?

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

有谁知道我怎么能让红色的灯罩有点透明?虽然我不需要它是完全透明的。

回答

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

请参阅采取4个参数(intfloat)以进一步细节Color constructors

1

试试这个:

protected void paintComponent(Graphics 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); 

    } 
}