Question

I'm drawing several shapes in different colors, using a single instance of Paint. I would like the alpha value (< 255) of each painted region to be the same. I set the desired alpha value when initializing the Paint. However, whenever I change the color of my Paint using setColor, the alpha value of my paint is reset to 255 (fully opaque).

The following code demonstrates this issue:

myPaint.setAlpha(100);

// myPaint.getAlpha() returns 100, as expected;

myPaint.setColor(Color.DKGRAY);

// myPaint.getAlpha() now returns 255;

Why does this happen? Will there be any impact on performance if I am forced to call paint.setAlpha(...) every time I change the paint color?

Was it helpful?

Solution

This is because the color you are using is of format argb. See the Paint and Color javadoc. You need to specify a color with just RGB or set the color alpha to the value you want to use. And it shouldn't be much of performance hit if you set the alpha each time, if you want to go that route.

As an added example you could do

paint.setColor(new Color(100, Color.red(Color.DKGRAY), Color.green(Color.DKGRAY), Color.blue(Color.DKGRAY)));

If you were going to always set the color to something like dark gray I would say you are better off creating a color resource with the values you want and using it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top