开发者

Java color opacity

I have a method to determine a color based on some value. The method is as such:

public Color color(double val) {
    double H = val * 0.3; 
    double S = 0.9; 
    double B = 0.9; 
    return Color.getHSBColor((float)H, (floa开发者_如何学Pythont)S, (float)B);
}

I also want to make the color created trasparent. How can I do this? Thanks


The easiest way is to specify R, G, B, and A directly, using this constructor:

public Color(float r, float g, float b, float a).

I know you have HSB, but you can convert to RGB easily enough.


I know this is old, but all I do when I want opacity made with the Java built-in Graphics Object, is new Color(RRR, GGG, BBB, AAA).

Used in context:

g.setColor(new Color(255, 255, 255, 80));

Last value is alpha channel/opacity, higher number means more opaque.


Use the Color constructor that takes a value with an alpha channel. Specifically, first you convert your color coordinates to RGB space:

int rgba = Color.HSBtoRGB(H, S, B);

and then add the desired amount of transparency,

rgba = (rgba & 0xffffff) | (alpha << 24);

where alpha is an integer between 0 (fully transparent) and 255 (fully opaque), inclusive. This value you can pass to the Color constructor, making sure to give true for the second argument.

Color c = new Color(rgba, true);


public Color color(double val) {
    double H = val * 0.3; 
    double S = 0.9; 
    double B = 0.9; 
    int rgb = Color.HSBtoRGB((float)H, (float)S, (float)B);
    int red = (rgb >> 16) & 0xFF;
    int green = (rgb >> 8) & 0xFF;
    int blue = rgb & 0xFF;
    Color color = new Color(red, green, blue, 0x33);
    return color;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜