【问题标题】:How to make a rectangle in Graphics in a transparent colour?如何在图形中以透明颜色制作矩形?
【发布时间】:2011-12-27 23:59:40
【问题描述】:

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

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

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

【问题讨论】:

    标签: java swing colors paintcomponent translucency


    【解决方案1】:
    int alpha = 127; // 50% transparent
    Color myColour = new Color(255, value, value, alpha);
    

    有关更多详细信息,请参阅采用 4 个参数(intfloat)的 Color constructors

    【讨论】:

      【解决方案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); 
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2020-10-09
        • 1970-01-01
        • 2022-01-06
        • 2016-05-25
        • 2016-10-05
        • 1970-01-01
        • 1970-01-01
        • 2021-03-21
        • 2012-06-20
        相关资源
        最近更新 更多