Pra*_*mar 9 android screenshot path paint android-canvas
我正在开发一个在设备中截取屏幕截图的应用程序.在这个应用程序中,我们可以在屏幕上绘制任何内容.为此,我使用Canvas,Paint和Path来执行此操作.
我正在使用此代码截取屏幕截图:
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;
}
Run Code Online (Sandbox Code Playgroud)
但是,运行以下行时:
Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
Run Code Online (Sandbox Code Playgroud)
我的应用程序因以下异常而关闭:
11-28 15:05:46.291: E/AndroidRuntime(8209): java.lang.IllegalArgumentException: width and height must be > 0
Run Code Online (Sandbox Code Playgroud)
如果我更改高度和宽度,则会截取屏幕截图,但它是空的:

为什么会这样?我究竟做错了什么?
Lal*_*ani 18
你可以这样做,
为您的主布局提供ID并在屏幕上显示内容后,在一些Listener说按钮单击或菜单项或任何此类监听器上写下面的代码(确保在显示布局后调用这些行,否则它将给出一个黑屏).
View content = findViewById(R.id.myLayout);
content.setDrawingCacheEnabled(true);
getScreen(content);
Run Code Online (Sandbox Code Playgroud)
方法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();
}
}
Run Code Online (Sandbox Code Playgroud)
也不要添加将文件写入SDCard的权限.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
</uses-permission>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4348 次 |
| 最近记录: |