jpo
jpo

Reputation: 4059

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, (float)S, (float)B);
}

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

Upvotes: 4

Views: 50803

Answers (4)

user6412105
user6412105

Reputation: 61

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.

Upvotes: 6

David Z
David Z

Reputation: 131550

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

Upvotes: 4

Ray Toal
Ray Toal

Reputation: 88378

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.

Upvotes: 9

jpo
jpo

Reputation: 4059

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

Upvotes: 1

Related Questions