android实现截屏分享,Android截屏、保存、分享
android实现截屏分享,Android截屏、保存、分享
原理:将截取到的Bitmap赋给Dialog上的ImageView,并对Dialog加了弹出和收起的动画,实现截屏效果。
首先创建一个layout名为show_cut_screen_layout用于弹出截图对话框,上面是一个image,下面是横向线性布局的两个button。
然后设置对话框弹出的style:
进入values——style.xml里面添加如下代码:
接下来在res文件夹下新建一个anim文件夹用于保存对话框弹出和收起动画:
在里面新建popview_in_amin.xml :
和popview_out_amin.xml :
接下来是java代码:
//截屏功能
private void popShotSrceenDialog(){
final AlertDialog cutDialog = new AlertDialog.Builder(this).create();
View dialogView = View.inflate(this, R.layout.show_cut_screen_layout, null);
ImageView showImg = (ImageView) dialogView.findViewById(R.id.show_cut_screen_img);
dialogView.findViewById(R.id.share_cancel).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cutDialog.dismiss();
}
});
dialogView.findViewById(R.id.share_img).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//分享
Uri pa=Uri.fromFile(new File(filePath));//根据路径转化为uri
Intent imageIntent = new Intent(Intent.ACTION_SEND);//调用系统的ACTION_SEND
imageIntent.setType("image/png");
imageIntent.putExtra(Intent.EXTRA_STREAM, pa);//EXTRA_STREAM对应转化为uri的path
startActivity(Intent.createChooser(imageIntent, "分享"));
}
});
//获取当前屏幕的大小
int width = getWindow().getDecorView().getRootView().getWidth();
int height = getWindow().getDecorView().getRootView().getHeight();
//生成相同大小的图片
Bitmap temBitmap = Bitmap.createBitmap( width, height, Bitmap.Config.ARGB_8888 );
//找到当前页面的跟布局
View view = getWindow().getDecorView().getRootView();
//设置缓存
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
//从缓存中获取当前屏幕的图片
temBitmap = view.getDrawingCache();
//保存图片
if (temBitmap != null)
{
try {
// 获取内置SD卡路径
String sdCardPath = Environment.getExternalStorageDirectory().getPath();
// 图片文件路径,获取系统时间
long time=System.currentTimeMillis();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
java.util.Date date=new java.util.Date(time);
String str=sdf.format(date);
filePath = sdCardPath + File.separator +str+"screenshot.png";
File file = new File(filePath);
FileOutputStream os = new FileOutputStream(file);
temBitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
os.flush();
os.close();
} catch (Exception e) {
Toast.makeText(be_qrcode.this,"保存失败,请检查权限或清理内存",Toast.LENGTH_SHORT).show();
}
}
showImg.setImageBitmap(temBitmap);
cutDialog.setView(dialogView);
Window window = cutDialog.getWindow();
window.setBackgroundDrawableResource(android.R.color.transparent);
WindowManager m = window.getWindowManager();
Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
WindowManager.LayoutParams p = window.getAttributes(); // 获取对话框当前的参数值
p.height = (int) (d.getHeight() * 0.8); // 高度设置为屏幕的0.6
p.gravity = Gravity.CENTER;//设置弹出框位置
window.setAttributes(p);
window.setWindowAnimations(R.style.dialogWindowAnim);
cutDialog.show();
}