user1855796
user1855796

Reputation:

imageview DrawingCache returns null

i'm using DrawingCache but it gives me NullPointerException

my code is as below:

    myImageView.setDrawingCacheEnabled(true);

    myImageView.buildDrawingCache();
    resized = myImageView.getDrawingCache();        
    btnSave.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            String save_location = Environment
                    .getExternalStorageDirectory().getAbsolutePath()
                    + "/EditedImage";
            File dir = new File(save_location);
            if (!dir.exists())
                dir.mkdirs();
            File f = new File(dir, TEMP_PHOTO_FILE);
            FileOutputStream out;
            try {
                out = new FileOutputStream(f);
                resized.compress(Bitmap.CompressFormat.PNG, 90, out);

                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

error is at onClick.

my logcat is enter image description here what is missing in this?

Upvotes: 1

Views: 1622

Answers (2)

secretlm
secretlm

Reputation: 2361

Try this examle:

myImageView.setDrawingCacheEnabled(true);

myImageView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 
            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
myImageView.layout(0, 0, v.getMeasuredWidth(), myImageView.getMeasuredHeight()); 

myImageView.buildDrawingCache(true);


Bitmap b = Bitmap.createBitmap(myImageView.getDrawingCache());
myImageView.setDrawingCacheEnabled(false); // clear drawing cache

Updated:

Another way, you can create a Canvas for the Bitmap and then call view.draw(canvas) like:

 public static Bitmap loadBitmapFromView(View v) {
         Bitmap b = Bitmap.createBitmap( v.getLayoutParams().width, v.getLayoutParams().height,              Bitmap.Config.ARGB_8888);                


         Canvas c = new Canvas(b);
         v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
         v.draw(c);
         return b;
    }

Upvotes: 1

faylon
faylon

Reputation: 7450

Each view will take some procedure, for example, measure and layout, before it is drew on screen. So when you invoke getDrawingCache() in Activity.onCreate(), the view is not drew yet.

Put the following two lines in your onclick method.

myImageView.buildDrawingCache();
resized = myImageView.getDrawingCache();

Upvotes: 0

Related Questions