Android实现全屏截图或长截屏功能
本文实例为大家分享了Android实现全屏截图或长截屏功能的具体代码,供大家参考,具体内容如下
全屏截图:
/** *传入的activity是要截屏的activity */ publicstaticBitmapgetViewBitmap(Activityactivity){ //View是你需要截图的View Viewview=activity.getWindow().getDecorView(); //这两句必须写,否则getDrawingCache报空指针 view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmapb1=view.getDrawingCache(); //获取状态栏高度 Rectframe=newRect(); activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); intstatusBarHeight=frame.top; //获取屏幕长和高 intwidth=activity.getResources().getDisplayMetrics().widthPixels; intheight=activity.getResources().getDisplayMetrics().heightPixels; //去掉标题栏 Bitmapb=Bitmap.createBitmap(b1,0,statusBarHeight,width,height-statusBarHeight); view.destroyDrawingCache(); returnb; }
ScrollView或者ListView或者LinearLayout等ViewGroup的长截图:
publicstaticBitmapgetViewGroupBitmap(ViewGroupviewGroup){ //viewGroup的总高度 inth=0; Bitmapbitmap; //适用于ListView或RecyclerView等求高度 for(inti=0;i总结:
1.布局为ScrollView,ListView,RecyclerView等能滑动的,用for循环遍历子元素求实际高度。
ps:ScrollView由于只能有一个直接子元素,那么我们可以直接用他的子元素来求高度。
2.布局为LinearLayout等ViewGroup,直接.getHeight()获取注意:
1.getHeight(),getWidth()不能直接在avtivity生命周期中调用,因为activity尚未生成完毕之前,控件的长宽尚未测量,故所得皆为0
2.用该方式实现长截屏需要注意背景色的问题,如果你的截图背景色出了问题,仔细检查XML文件,看看该背景色是否设置在你截屏的控件中补充:
对于混合布局比如说:根RelativeLayout布局中有ViewGroup+RelativeLayout等子布局,可以分别测量他们的高度并生成bitmap对象,然后拼接在一起即可。
/** *上下拼接两个Bitmap, *drawBitmap的参数:1.需要画的bitmap *2.裁剪矩形,bitmap会被该矩形裁剪 *3.放置在canvas的位置矩形,bitmap会被放置在该矩形的位置上 *4.画笔 */ publicstaticBitmapmergeBitmap_TB_My(BitmaptopBitmap,BitmapbottomBitmap){ intwidth=topBitmap.getWidth(); intheight=topBitmap.getHeight()+bottomBitmap.getHeight(); Bitmapbitmap=Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888); Canvascanvas=newCanvas(bitmap); RectrectTop=newRect(0,0,width,topBitmap.getHeight()); RectrectBottomRes=newRect(0,0,width,bottomBitmap.getHeight()); RectFrectBottomDes=newRectF(0,topBitmap.getHeight(),width,height); canvas.drawBitmap(topBitmap,rectTop,rectTop,null); canvas.drawBitmap(bottomBitmap,rectBottomRes,rectBottomDes,null); returnbitmap; }以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。