/*
* Copyright(c) 2017 lizhaotailang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.marktony.espresso.util;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Point;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Display;
import android.view.WindowManager;
import java.lang.reflect.InvocationTargetException;
/**
* Created by lizhaotailang on 2017/3/24.
*/
public class DensityUtil {
public static int getScreenHeight(Context context) {
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
return displayMetrics.heightPixels;
}
public static int getScreenWidth(Context context) {
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
return displayMetrics.widthPixels;
}
public static int getScreenHeightWithDecorations(Context context) {
int heightPixes;
WindowManager windowManager = ((Activity) context).getWindowManager();
Display display = windowManager.getDefaultDisplay();
Point realSize = new Point();
try {
Display.class.getMethod("getRealSize", Point.class).invoke(display, realSize);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
heightPixes = realSize.y;
return heightPixes;
}
public static int dip2px(Context context, float dpVale) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpVale * scale + 0.5f);
}
public static int getStatusBarHeight(Context context) {
Resources resources = context.getResources();
int resourcesId = resources.getIdentifier("status_bar_height", "dimen", "android");
int height = resources.getDimensionPixelSize(resourcesId);
return height;
}
/**
* Converts sp to px
*
* @param context Context
* @param sp the value in sp
* @return int
*/
public static int dip2sp(Context context, float sp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, context.getResources().getDisplayMetrics());
}
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
}