Android开发之屏幕截图保存至SD卡
相信我们大家都有过这样的经历,在我们做一个默默地低头族,把玩手机时,遇到自己感兴趣的事务,总想一键截屏,把美好的事务保存起来,由此,本人研究了下如何截取手机屏幕并保存呢,经研究,已实现其功能,现将代码贴出,望各位大神,批评指正,灰常感谢♪(^∇^*)核心代码: MainActivity
package com.hxht.testgetcurrentscreen;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.Toast;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void getScreen(View view) {
//拿到状态栏的高度
Rect rect = new Rect();
MainActivity.this.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
int statusBarHeights = rect.top;
Display display = MainActivity.this.getWindowManager().getDefaultDisplay();
// 获取屏幕宽和高
int width = display.getWidth();
int height = display.getHeight();
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd_HH-mm-ss", Locale.US);
String fname = "/sdcard/" + sdf.format(new Date()) + ".png";
View rootView = view.getRootView();
rootView.setDrawingCacheEnabled(true);
rootView.buildDrawingCache();
Bitmap bitmap = rootView.getDrawingCache();
bitmap = Bitmap.createBitmap(bitmap, 0, statusBarHeights, width, height - statusBarHeights);
if (bitmap != null) {
Toast.makeText(this, "获取当前屏幕成功", Toast.LENGTH_SHORT).show();
try {
FileOutputStream out = new FileOutputStream(fname);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(this, "获取当前屏幕失败", Toast.LENGTH_SHORT).show();
}
}
}
代码已贴出,正所谓取之于社会,回报于社会,望各位大神批评指正,不喜勿喷,灰常感谢♪(^∇^*)