Custom convert a view to a bitmap that returns a black image

I need to create my own view and then save it in a png file to an SD card. Right now I am getting black color images in an SD card. I could not trace the problem in the code. Can anybody help me.

layout file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:orientation="vertical" >
        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/black" />

        <TextView
            android:id="@+id/address"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/black" />
</LinearLyout>

In my java file, I inflated the linear layout and set the data in textviews, and then call:

private Bitmap convertViewToBitmap(LinearLayout layout) {
    layout.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
    int width = layout.getMeasuredWidth();
    int height = layout.getMeasuredHeight();

    //Create the bitmap
    Bitmap bitmap = Bitmap.createBitmap(width, 
            height, 
            Bitmap.Config.ARGB_8888);
    //Create a canvas with the specified bitmap to draw into
    Canvas c = new Canvas(bitmap);

    //Render this view (and all of its children) to the given Canvas
    view.draw(c);
    return bitmap;
}

After receiving the bitmap, I save it on the SD card as follows:

private void saveBitmapTpSdCard(Bitmap bitmap, String fileName) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 40, bytes);

        File f = new File(Environment.getExternalStorageDirectory()
                + File.separator + getString(R.string.app_name));

        try {
            if(!f.exists()) {
                f.mkdirs();
            }
            File imageFile = new File(f, fileName + ".png");
            FileOutputStream fo = new FileOutputStream(imageFile);
            fo.write(bytes.toByteArray());
            fo.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
}
+4
source share
3 answers

I processed this by adding this line:

view.layout(0, 0, width, height);

before creating a bitmap using Bitmap.createBitmap

+3
source

Bitmap:

    LinearLayout layout = (LinearLayout) findViewById(R.id.layout_main_for_bitmap);
    layout.setDrawingCacheEnabled(true);
    layout.buildDrawingCache();
    Bitmap bitmap = layout.getDrawingCache();
0

, LinearLayout , , (.. layout ). , ViewGroup, .

, , linearLayout.post() LinearLayout ( , ) Runnable "".

layout.

0

Source: https://habr.com/ru/post/1539711/


All Articles