最近项目比较紧,周六还在公司加班,需求里面有截图这个功能,于是便开始搞,网上搜了下,发现2个方法,并亲测可用,分享给大家
1、简单的屏幕截取并保存(对view截取的部分为黑的)
代码如下:
private void getScreenHot(View v, String filePath)
{
try
{
Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas();
canvas.setBitmap(bitmap);
v.draw(canvas);
try
{
FileOutputStream fos = new FileOutputStream(filePath);
bitmap.compress(CompressFormat.PNG, 100, fos);
}
catch (FileNotFoundException e)
{
throw new InvalidParameterException();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
2、对mapview进行截屏
将mapview转化为bitmap,代码如下:
private Bitmap getViewBitmap(MapView v) {
v.clearFocus();
v.setPressed(false);
//能画缓存就返回false
boolean willNotCache = v.willNotCacheDrawing();
v.setWillNotCacheDrawing(false);
int color = v.getDrawingCacheBackgroundColor();
v.setDrawingCacheBackgroundColor(0);
if (color != 0) {
v.destroyDrawingCache();
}
v.buildDrawingCache();
Bitmap cacheBitmap = null;
while(cacheBitmap == null){
cacheBitmap = v.getDrawingMapCache(0, 0, v.getWidth(), v.getHeight());
}
Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
// Restore the view
v.destroyDrawingCache();
v.setWillNotCacheDrawing(willNotCache);
v.setDrawingCacheBackgroundColor(color);
return bitmap;
}
然后处理存储的文件名以及保存到sd卡,此处采用日期加时间存储,精确到秒。
private void mapviewshot() {
System.out.println("进入截屏方法");
Date date=new Date();
SimpleDateFormat dateformat1=new SimpleDateFormat("yyyyMMdd_hhmmss");
String timeString=dateformat1.format(date);
String path="arcgis/screenshot";
String externalPath=Environment.getExternalStorageDirectory().toString();
String filename=externalPath+"/"+path+"/"+timeString;
File file_2=new File(externalPath+"/"+path);
if (!file_2.exists()){
System.out.println("path 文件夹 不存在--开始创建");
file_2.mkdirs();
}
filename=getfilepath(filename);//判断是否有同一秒内的截图,有就改名字
//存储于sd卡上
System.out.println("获得的filename--"+filename);
Bitmap bitmap=getViewBitmap(mMapView);
File file=new File(filename);
try {
FileOutputStream fileOutputStream=new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private String getfilepath(String filename) {
String filestr=filename+".png";
File file=new File(filestr);
if (file.exists()){
filename=getfilepath(filename+"_1");
}
else {
filename=filestr;
}
System.out.println("getfilename函数返回----"+filename);
return filename;
}
特别感谢http://www.cnblogs.com/wangcan/p/3457914.html,希望大家以后有好的方法也多做分享