2011-11-13 108 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); 

    } 
}