Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing the snapshot of the Relative layout with transparent background gives a bitmap with black background not transparent

Tags:

android

I have a Relative layout with transparent background which contains images,text etc when i capture its bitmap by using Drawing cache or canvas the transparent color get converted to black i have tried lots of means but no success...

rl_mainCanvesLayout.setDrawingCacheBackgroundColor(Color.TRANSPARENT);
Bitmap bitmap =Bitmap.createBitmap(rl_mainCanvesLayout.getDrawingCache());
rl_mainCanvesLayout.setDrawingCacheEnabled(false);
Bitmap bitmap = Bitmap.createBitmap(rl_mainCanvesLayout.getDrawingCache());

private String savebitmap(Bitmap bitmap, String filename) {
    String dir = Environment.getExternalStorageDirectory() + File.separator  + "abc";
    File file_dir = new File(dir);
    file_dir.mkdir();
    FileOutputStream outStream = null;
    File file = new File(dir, filename + ".jpg");
    if (file.exists()) {
        file.delete();
        file = new File(dir, filename + ".jpg");
        Log.e("file exist", "" + file + ",Bitmap= " + filename);
    }
    try {
        outStream = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
        outStream.flush();
        outStream.close();

    } catch (Exception e) {
        e.printStackTrace();

    }
    Log.e("file", "" + file);
    return file.toString();

}
like image 828
Arun Salaria Avatar asked Nov 20 '15 08:11

Arun Salaria


1 Answers

According to the source of the getDrawingCache() method, it ends up in buildDrawingCache() after a few calls, this is where the real work is done. Here, it creates a bitmap then draw it by a canvas. In your situation you set transparent color, which is equal to 0, as for this, it does NOT set the returned bitmap's color map(at line 14450 eraseColor not called), it leaves it at default value. Later as it draws your layout, it does NOT take care about ANYTHING except itself and it's children. As consequence of this, you get the black background as those pixels are not assigned.

A possible workorund for this, is to set different drawingCacheBackgroundColor, which value is not 0, or set a color attribute for the relative layout. By these, you can get the desired background color.

If your intention was to get a snapshot of the layout and it's real background(other views, activty etc.), then you should get drawing cache from it's parent and apply it to this layout's drawing cache with image editing or just simply take a screenshot and crop the layout's area.

like image 178
csenga Avatar answered Oct 28 '22 04:10

csenga