Kamloops
Kamloops

Reputation: 437

Using bitmap as an alpha for Layout

I would like to use a bitmap as an aplha on a Layout. If I use for exemple a Layout with a background color and an Imageview or another Layout on top on this one, I would like to display a shape using an aplha mask. A picture's worth a thousand words :

https://zupimages.net/up/18/34/3zii.jpg

I've look into Canvas.drawBitmap but I can't figure out how I could do with it

Do you think it's possible ? Thanks

PS : This is just an example, the alpha bitmap is actually way more complicated (I can't just put a TextView)

Upvotes: 1

Views: 64

Answers (1)

Yohann L.
Yohann L.

Reputation: 1451

Here is a function which could work for you :

public static Bitmap makeTransparent(Bitmap bit, Bitmap mask) {
    int width =  bit.getWidth();
    int height = bit.getHeight();
    Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    int [] allpixels = new int [ bmp.getHeight()*bmp.getWidth()];
    bit.getPixels(allpixels, 0, bmp.getWidth(), 0, 0, bmp.getWidth(),bmp.getHeight());
    bmp.setPixels(allpixels, 0, width, 0, 0, width, height);

    Bitmap bmpM = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    int [] allpixelsM = new int [ bmpM.getHeight()*bmpM.getWidth()];
    mask.getPixels(allpixelsM, 0, bmpM.getWidth(), 0, 0, bmpM.getWidth(),bmpM.getHeight());
    bmpM.setPixels(allpixelsM, 0, width, 0, 0, width, height);

    for(int i =0; i<bmp.getHeight()*bmp.getWidth();i++) {
        int A = (allpixelsM[i] >> 16) & 0xff;
        int R = (allpixels[i] >> 16) & 0xff;
        int G = (allpixels[i] >> 8) & 0xff;
        int B = (allpixels[i]) & 0xff;
        allpixels[i] = Color.argb(A, R, G, B);
    }

    bmp.setPixels(allpixels, 0, bmp.getWidth(), 0, 0, bmp.getWidth(), bmp.getHeight());
    return bmp;
}

Upvotes: 1

Related Questions