Alin
Alin

Reputation: 14581

Android custom view save visible screen to bitmap

In my app the user manipulates a image, rotates, pinch, zoom etc. This is make within onDraw() using canvas.translate(), canvas.rotate() etc. Of course the image is big and after the manipulation of the image the user performs interactions with other Views. The thing is I don't want to redraw the whole big image over and over again only the visible part. So I'd like, after the user finishes operations, SAVE the current VISIBLE image on the screen to memory/bitmap/cache and redraw only that.

How can I achieve this ?

Upvotes: 1

Views: 4873

Answers (4)

Shraddha
Shraddha

Reputation: 1052

Following may help you :

(1)

 View v = view.getRootView();
    v.setDrawingCacheEnabled(true);
    Bitmap b = v.getDrawingCache();

(2) This is a similar to another question at How to capture the android device screen content?

(3) You can try using this library http://code.google.com/p/android-screenshot-library/ It introduces an Android Screenshot Library (ASL) which enables to programmatically capture screenshots from Android devices without requirement of having root access privileges.

Upvotes: 0

Alin
Alin

Reputation: 14581

I've found a really great article about what I needed HERE

To kepp thing clear, first I need to create a bitmap with the size of my View, then create a canvas for it, draw on canvas and then save it.

public void saveScreenshot() {
            Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            canvas.draw(myGiganticImage)

            File file = new File(context.getFilesDir() + "/cache.jpg");
            FileOutputStream fos;
            try {
                fos = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
                fos.close();

                cachedBackground = BitmapFactory.decodeFile(context.getFilesDir()  + "/cache.jpg"
                invalidate()                
            } catch (FileNotFoundException e) {
            } catch (IOException e) {
            }
        }

I simply call this on onDraw() when I need it. It will save a bitmap on internal memory which I can use to draw, instead of the big picture.

Upvotes: 1

Abhinava
Abhinava

Reputation: 1030

In your on draw initialize your Canvas with a bitmap. keep a reference of this bitmap and save it whenever required.

Upvotes: 1

Thomas
Thomas

Reputation: 1508

In the constructor of your custom View, enable the drawing cache like this: setDrawingCacheEnabled(true);. Then whenever you want to save the state of your Canvas you can call getDrawingCache(), which returns the desired Bitmap.

Documentation: getDrawingCache()

Upvotes: 3

Related Questions