package com.example.screenshot;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button bt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = (Button) this.findViewById(R.id.bt);
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Bitmap bm = shot(MainActivity.this);
String path = "";
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
path = Environment.getExternalStorageDirectory().getAbsolutePath();
}else{
Toast.makeText(getApplicationContext(), "不存在内存卡", 1).show();
}
savaShot(bm, path);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private Bitmap shot(Activity activity) {
//View是你需要截图的View
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b1 = view.getDrawingCache();
// 获取状态栏高度
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
// 获取屏幕长和高
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
// 去掉标题栏
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);
view.destroyDrawingCache();
return b;
}
//保存截图
private void savaShot(Bitmap bitmap, String path){
SimpleDateFormat simple=new SimpleDateFormat("yyyyMMddhhmmss");
String time=simple.format(new Date());
FileOutputStream fos=null;
try{
File sddir=new File(path);
if(!sddir.exists()){
sddir.mkdir();
}
File file=new File(path + "/" + time + ".jpg");
fos=new FileOutputStream(file);
if(fos!=null){
bitmap.compress(Bitmap.CompressFormat.JPEG,100, fos);
fos.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
}