How to make a rectangle in Graphics in a transparent colour?

杀马特。学长 韩版系。学妹 提交于 2019-12-21 06:58:05

问题


I'm trying to paint a rectangle on my application in a red shade but I need to make it sort of transparent so that the component under it will still show. However I still want that some colour will still show. The method where I'm drawing is the following:

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

Does anyone know how I can make the red shade a bit transparent? I don't need it completely transparent though.


回答1:


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

See the Color constructors that take 4 arguments (int or float) for further details.




回答2:


Try this:

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

    }
}


来源:https://stackoverflow.com/questions/8110975/how-to-make-a-rectangle-in-graphics-in-a-transparent-colour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!