I am trying to change the alpha value of a bitmap per pixel in a for loop. The Bitmap is created from a createBitmap(source,x,y,w,h) of another bitmap. I’ve done a little test but I can’t seem to alter the alpha. Is it the setPixel command or the fact the bitmap it isn’t ARGB?
I want to create a simple fade out effect in the end but for now I am not referencing original pixel colors just green with half alpha. Thanks if you can help 🙂
_left[1] = Bitmap.createBitmap(TestActivity.photo, 0, 0, 256, 256);
for (int i = 0; i < _left[1].getWidth(); i++)
for (int t = 0; t < _left[1].getHeight(); t++) {
int a = (_left[1].getWidth() / 2) - i;
int b = (_left[1].getHeight() / 2) - t;
double dist = Math.sqrt((a*a) + (b*b));
if (dist > 20) _left[1].setPixel(i, t, Color.argb(128, 0, 255, 0));
}
UPDATE :
Okay this is the result I came up with if anyone wants to take a bitmap and fade out radially. But yes it is VERY SLOW without arrays… Thanks Reuben for a step in the right direction
public void fadeBitmap (Bitmap input, double fadeStartPercent, double fadeEndPercent, Bitmap output) {
Bitmap tempalpha = Bitmap.createBitmap(input.getWidth(), input.getHeight(), Bitmap.Config.ARGB_8888 );
Canvas printcanvas = new Canvas(output);
int radius = input.getWidth() / 2;
double fadelength = (radius * (fadeEndPercent / 100));
double fadestart = (radius * (fadeStartPercent / 100));
for (int i = 0; i < input.getWidth(); i++)
for (int t = 0; t < input.getHeight(); t++) {
int a = (input.getWidth() / 2) - i;
int b = (input.getHeight() / 2) - t;
double dist = Math.sqrt((a*a) + (b*b));
if (dist <= fadestart) {
tempalpha.setPixel(i,t,Color.argb(255, 255, 255, 255));
} else {
int fadeoff = 255 - (int) ((dist - fadestart) * (255/(fadelength - fadestart)));
if (dist > radius * (fadeEndPercent / 100)) fadeoff = 0;
tempalpha.setPixel(i,t,Color.argb(fadeoff, 255, 255, 255));
}
}
Paint alphaP = new Paint();
alphaP.setAntiAlias(true);
alphaP.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
// printcanvas.setBitmap();
printcanvas.drawBitmap(input, 0, 0, null);
printcanvas.drawBitmap(tempalpha, 0, 0, alphaP);
}
The version of
Bitmap.createBitmap()you are using returns an immutable bitmap.Bitmap.setPixel()will have no effect.setPixel is appallingly slow anyway. Aim to use setPixels(), or, best of all, find a better way than manipulating bitmap pixels directly. I expect you could do something clever with a separate alpha-only bitmap and the right PorterDuff mode.