Generate bitmap from view

113 views Asked by At

When I get the bitmap from the DrawingCache of a view I get no error but I don't see a valid bitmap either. What am I doing wrong?

The code I use to generate the bitmap:

SharePhotoView sharePhotoView = SharePhotoView_.build(this);
sharePhotoView.bind(mCatch);

sharePhotoView.setDrawingCacheEnabled(true);
sharePhotoView.buildDrawingCache();
Bitmap bitmap = sharePhotoView.getDrawingCache();

catchImage.setImageBitmap(bitmap);

The code I use to make the view:

@EViewGroup(R.layout.share_photo)
public class SharePhotoView extends LinearLayout{

    @ViewById
    ImageView catchImage;

    public SharePhotoView(Context context) {
        super(context);
    }

    public void bind(Catch catchItem) {
        Bitmap bitmap = BitmapFactory.decodeFile(catchItem.getImage().getPath());

        catchImage.setImageBitmap(bitmap);

    }
}
2

There are 2 answers

0
Bart Bergmans On BEST ANSWER

Found a method somewhere that did the trick:

public static Bitmap getScreenViewBitmap(View v) {
    v.setDrawingCacheEnabled(true);

    // this is the important code :)
    // Without it the view will have a dimension of 0,0 and the bitmap will be null
    v.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
    v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());

    v.buildDrawingCache(true);
    Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
    v.setDrawingCacheEnabled(false); // clear drawing cache

    return b;
}

Source: http://www.jattcode.com/getting-bitmap-from-a-view-visible-invisible-oncreate/

4
Santiago On

Use this code for a Bitmap from view:

Bitmap bitmap;
            try {
                bitmap = Bitmap.createBitmap(YOUR_VIEW.getWidth(), YOUR_VIEW.getHeight(),
                        Bitmap.Config.ARGB_8888);

                Canvas canvas = new Canvas(bitmap);
                YOUR_VIEW.draw(canvas);

                File root = Environment.getExternalStoragePublicDirectory(Environment.PICTURES);

                String fname = "NAME_OF_FILE.jpg";
                file = new File(root, fname);

                try {
                    if (!root.exists()) {
                    root.mkdir();
                }
                    FileOutputStream out = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                    out.flush();
                    out.close();
                    YOUR_VIEW.destroyDrawingCache();

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

            } catch (Exception e) {
            }