Convert view to an image. - Android User Interface

Android examples for User Interface:View Bitmap

Description

Convert view to an image.

Demo Code


//package com.java2s;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;

import android.util.Log;

import android.webkit.WebView;

public class Main {
    /**/*from w w w  . j  a  v  a 2s.  c om*/
     * Convert view to an image.  Can be used to make animations smoother.
     *
     * @param context           The current Context or Activity that this method is called from
     * @param viewToBeConverted View to convert to a Bitmap
     * @return Bitmap object that can be put in an ImageView.  Will look like the converted viewToBeConverted.
     */
    public static Bitmap viewToImage(Context context,
            WebView viewToBeConverted) {
        int extraSpace = 2000; //because getContentHeight doesn't always return the full screen height.
        int height = viewToBeConverted.getContentHeight() + extraSpace;

        Bitmap viewBitmap = Bitmap.createBitmap(
                viewToBeConverted.getWidth(), height,
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(viewBitmap);
        viewToBeConverted.draw(canvas);

        //If the view is scrolled, cut off the top part that is off the screen.
        try {
            int scrollY = viewToBeConverted.getScrollY();
            if (scrollY > 0) {
                viewBitmap = Bitmap.createBitmap(viewBitmap, 0, scrollY,
                        viewToBeConverted.getWidth(), height - scrollY);
            }
        } catch (Exception ex) {
            Log.e("PercolateAndroidUtils",
                    "Could not remove top part of the webview image.  ex="
                            + ex);
        }

        return viewBitmap;
    }
}

Related Tutorials