Android獲取手機螢幕引數的工具
阿新 • • 發佈:2019-02-18
package com.manny.utils;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.view.View;
/**
* Created by manny on 2017/12/28.
*/
public class ScreenUtils
{
private ScreenUtils()
{
/* cannot be instantiated */
throw new UnsupportedOperationException( “cannot be instantiated” );
}
/** * 獲得螢幕密度density */ public static float getDensity( Context context ) { return context.getResources().getDisplayMetrics().density; } /** * 獲得螢幕寬度 */ public static int getScreenWidth( Context context ) { return context.getResources().getDisplayMetrics().widthPixels; } /** * 獲得螢幕高度 */ public static int getScreenHeight( Context context ) { return context.getResources().getDisplayMetrics().heightPixels; } /** * 獲得狀態列的高度 */ public static int getStatusHeight( Context context ) { if( context != null ) { int statusBarHeight = 0; Resources res = context.getResources(); int resourceId = res.getIdentifier( "status_bar_height", "dimen", "android" ); if( resourceId > 0 ) { statusBarHeight = res.getDimensionPixelSize( resourceId ); } return statusBarHeight; } return -1; } /** * 獲取當前螢幕截圖,包含狀態列 */ public static Bitmap snapShotWithStatusBar( Activity activity ) { View view = activity.getWindow().getDecorView(); view.setDrawingCacheEnabled( true ); view.buildDrawingCache(); Bitmap bmp = view.getDrawingCache(); int width = getScreenWidth( activity ); int height = getScreenHeight( activity ); Bitmap bp = null; bp = Bitmap.createBitmap( bmp, 0, 0, width, height ); view.destroyDrawingCache(); return bp; } /** * 獲取當前螢幕截圖,不包含狀態列 */ public static Bitmap snapShotWithoutStatusBar( Activity activity ) { View view = activity.getWindow().getDecorView(); view.setDrawingCacheEnabled( true ); view.buildDrawingCache(); Bitmap bmp = view.getDrawingCache(); Rect frame = new Rect(); activity.getWindow().getDecorView().getWindowVisibleDisplayFrame( frame ); int statusBarHeight = frame.top; int width = getScreenWidth( activity ); int height = getScreenHeight( activity ); Bitmap bp = null; bp = Bitmap.createBitmap( bmp, 0, statusBarHeight, width, height - statusBarHeight ); view.destroyDrawingCache(); return bp; }
}