Android获取常用辅助方法(获取屏幕高度、宽度、密度、通知栏高度、截图)
我们需要获取Android手机或Pad的屏幕的物理尺寸,以便于界面的设计或是其他功能的实现。下面就分享一下Android中常用的一些辅助方法:
获取屏幕高度:
/** *获得屏幕高度 *@paramcontext *@return *byHankkinat:2015-10-0721:15:59 */ publicstaticintgetScreenWidth(Contextcontext){ WindowManagerwm=(WindowManager)context .getSystemService(Context.WINDOW_SERVICE); DisplayMetricsoutMetrics=newDisplayMetrics(); wm.getDefaultDisplay().getMetrics(outMetrics); returnoutMetrics.widthPixels; }
获取屏幕宽度:
/** *获得屏幕宽度 *@paramcontext *@return *byHankkinat:2015-10-0721:16:13 */ publicstaticintgetScreenHeight(Contextcontext){ WindowManagerwm=(WindowManager)context .getSystemService(Context.WINDOW_SERVICE); DisplayMetricsoutMetrics=newDisplayMetrics(); wm.getDefaultDisplay().getMetrics(outMetrics); returnoutMetrics.heightPixels; }
获取屏幕密度:
/** *获取屏幕密度 *@paramcontext *@return *byHankkinat:2015-10-0721:16:29 */ publicstaticfloatgetScreenDensity(Contextcontext){ returncontext.getResources().getDisplayMetrics().density; }
dip转px:
/** *dip转px像素 *@paramcontext *@parampx *@return *byHankkinat:2015-10-0721:16:43 */ publicstaticintdip2px(Contextcontext,floatpx){ finalfloatscale=getScreenDensity(context); return(int)(px*scale+0.5); }
获取状态栏高度:
/** *获得状态栏的高度 *@paramcontext *@return *byHankkinat:2015-10-0721:16:43 */ publicstaticintgetStatusHeight(Contextcontext){ intstatusHeight=-1; try{ Class<?>clazz=Class.forName("com.android.internal.R$dimen"); Objectobject=clazz.newInstance(); intheight=Integer.parseInt(clazz.getField("status_bar_height") .get(object).toString()); statusHeight=context.getResources().getDimensionPixelSize(height); }catch(Exceptione){ e.printStackTrace(); } returnstatusHeight; }
获取屏幕当前截图:
/** *获取当前屏幕截图,包含状态栏 *@paramactivity *@return *byHankkinat:2015-10-0721:16:43 */ publicstaticBitmapsnapShotWithStatusBar(Activityactivity){ Viewview=activity.getWindow().getDecorView(); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmapbmp=view.getDrawingCache(); intwidth=getScreenWidth(activity); intheight=getScreenHeight(activity); Bitmapbp=null; bp=Bitmap.createBitmap(bmp,0,0,width,height); view.destroyDrawingCache(); returnbp; } /** *获取当前屏幕截图,不包含状态栏 *@paramactivity *@return *byHankkinat:2015-10-0721:16:43 */ publicstaticBitmapsnapShotWithoutStatusBar(Activityactivity){ Viewview=activity.getWindow().getDecorView(); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmapbmp=view.getDrawingCache(); Rectframe=newRect(); activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); intstatusBarHeight=frame.top; intwidth=getScreenWidth(activity); intheight=getScreenHeight(activity); Bitmapbp=null; bp=Bitmap.createBitmap(bmp,0,statusBarHeight,width,height -statusBarHeight); view.destroyDrawingCache(); returnbp; }
以上所述是本文给大家介绍的Android获取常用辅助方法(获取屏幕高度、宽度、密度、通知栏高度、截图),希望对大家也是帮助,更多信息登录毛票票网站了解更多信息。