我正在开发一个在设备上截图的应用程序。在这个应用程序中,我们可以在屏幕上绘制任何内容。为此,我使用画布,绘画和路径来做这件事。
我使用下面的代码来截图:
public void saveScreenshot()
{
if (ensureSDCardAccess())
{
Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
onDraw(canvas);
File file = new File(mScreenshotPath + "/" + System.currentTimeMillis() + ".jpg");
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.e("Panel", "FileNotFoundException", e);
} catch (IOException e) {
Log.e("Panel", "IOEception", e);
}
}
}
/**
* Helper method to ensure that the given path exists.
* TODO: check external storage state
*/
private boolean ensureSDCardAccess() {
File file = new File(mScreenshotPath);
if (file.exists()) {
return true;
} else if (file.mkdirs()) {
return true;
}
return false;
}但是,当运行以下代码行时:
Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);我的应用程序关闭,但出现以下异常:
11-28 15:05:46.291: E/AndroidRuntime(8209): java.lang.IllegalArgumentException: width and height must be > 0如果我更改高度和宽度,屏幕截图将被截取,但它是空的:

为什么会发生这种情况?我做错了什么?
发布于 2011-12-03 15:12:01
你可以这样做,
给出主布局的id &在屏幕上显示内容后,在一些侦听器上编写以下代码,比如按钮单击或菜单项或任何此类侦听器(确保在布局显示后调用这些行,否则会出现空白屏幕)。
View content = findViewById(R.id.myLayout);
content.setDrawingCacheEnabled(true);
getScreen(content);方法内容(GetScreen)
private void getScreen(View content)
{
Bitmap bitmap = content.getDrawingCache();
File file = new File("/sdcard/test.png");
try
{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, ostream);
ostream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}也不要给SDCard添加写文件的权限。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
</uses-permission>发布于 2011-11-28 18:10:56
异常是因为您正在创建的Bitmap的高度和宽度为零
尝试下面的代码来获取高度和宽度
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();以防无法访问getWindowManager
Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();发布于 2011-11-28 18:09:29
getWidth(),getHeight()需要在上下文中调用,如果您在活动之外尝试它,它将失败。尝试使用getApplicationContext.getWidth()。
https://stackoverflow.com/questions/8294110
复制相似问题