我正在使用DrawingCache,但它给了我NullPointerException
我的代码如下:
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();
}
}
});
错误发生在onClick上。
我的logcat是
这个缺少什么?
答案 0 :(得分:1)
试试这个例子:
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
更新:
另一种方法是,你可以为Bitmap创建一个Canvas,然后调用view.draw(canvas),如:
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;
}
答案 1 :(得分:0)
每个视图在绘制到屏幕之前都会采用一些程序,例如测量和布局。因此,当您在Activity.onCreate()中调用getDrawingCache()时,视图尚未绘制。
在onclick方法中添加以下两行。
myImageView.buildDrawingCache();
resized = myImageView.getDrawingCache();