Android 2.1 View's getDrawingCache() method al

2020-01-26 09:54发布

I'm working with Android 2.1 and have the following problem: Using the method View.getDrawingCache() always returns null. getDrawingCache() should return a Bitmap, which is the presentation of View's content.

Example code:

public void onCreate(final Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  setContentView(R.layout.main);

  final View view = findViewById(R.id.ImageView01);
  view.setDrawingCacheEnabled(true);
  view.buildDrawingCache();
  final Bitmap bmp = view.getDrawingCache();
  System.out.println(bmp);

}

I've already tried different ways to configure the View object for generating the drawing cache (e.g. View.setWillNotDraw(boolean) and View.setWillNotCacheDrawing(boolean)), but nothing works.

What is the right way, or what I'm doing wrong?

PS: In real code I want to apply getDrawingCache() on a ViewGroup like RelativeLayout. Is the behaviour the same when using a ViewGroup?

7条回答
Melony?
2楼-- · 2020-01-26 10:03

use

onLayout(x, y, width, height);

for ex:

onLayout(0, 0, 100, 100);

before calling getDrawingCache

查看更多
放我归山
3楼-- · 2020-01-26 10:14

had the same problem and finally this partly works for me:

view.layout(0, 0, 1000, 100);
Bitmap b = view.getDrawingCache();
try {
    b.compress(CompressFormat.JPEG, 95,
    new FileOutputStream( Environment.getExternalStorageDirectory()                                                            + "/folder/name.jpg"));
catch (FileNotFoundException e) {
    Log.e(LOGTAG, "error:" + e.getMessage());
    }

the only problem is, that I can't get the full dimensions of my view. view.getwidth returns null ...

查看更多
不美不萌又怎样
4楼-- · 2020-01-26 10:18

As far as I read the last days in the documentation you should onlycall setDrawingCacheEnabled or buildDrawingChache() but not both.

查看更多
再贱就再见
5楼-- · 2020-01-26 10:18

Check out if your view is not bigger than the screen size. I found this and switched the dimensions of my view so, now it works =) Android get full View as Bitmap

查看更多
走好不送
6楼-- · 2020-01-26 10:20

Never do these things in onCreate! You can do it in a View.onClickListener or other place.

查看更多
女痞
7楼-- · 2020-01-26 10:23
Bitmap screenshot;
view.setDrawingCacheEnabled(true);
screenshot = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);

You need Bitmap.createBitmap(view.getDrawingCache()); as the Bitmap from which the reference is received by getDrawingCache() gets recycled.

查看更多
登录 后发表回答