오늘도 공부
현재 Activity 화면을 Bitmap으로 SD카드로 저장하기 본문
In this post I’ll show how you can take a screenshot of your current Activity and save the resulting image on /sdcard.
The idea behind taking a screenshot actually is pretty simple: what we need to do is to get a reference of the root view and generate a bitmap copy of this view.
Considering that we want to take the screenshot when a button is clicked, the code will look like this:
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
}
});
First of all we should retrieve the topmost view in the current view hierarchy, then enable the drawing cache, and after that call getDrawingCache().
Calling getDrawingCache(); will return the bitmap representing the view or null if cache is disabled, that’s why setDrawingCacheEnabled(true); should be set to true prior invoking getDrawingCache().
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
And the method that saves the bitmap image to external storage:
public void saveBitmap(Bitmap bitmap) {
File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
Since the image is saved on external storage, the WRITE_EXTERNAL_STORAGE permission should be added AndroidManifest to file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /
'Android > Tip&Tech' 카테고리의 다른 글
| Eclipse 자주 쓰는 단축키 (0) | 2013.08.26 |
|---|---|
| [펌]안드로이드/Android 터치 이벤트(Touch Event) 에서 Touch, LongTouch 동시에 구현 하기 ~! (0) | 2013.08.20 |
| XML Selector를 자바코드로 변경 (0) | 2013.08.13 |
| [펌]Preferences 관련 자료 (0) | 2013.07.29 |
| 위젯 관련 ppt (0) | 2013.07.22 |

