com.hadoopz.MyDroidLib.util.DisplayUtil Maven / Gradle / Ivy
/*
* Copyright 2017 jw362j.
*
* 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 com.hadoopz.MyDroidLib.util;
/**
*
* @author jw362j
*/
import android.content.Context;
/**
* dp、sp 转换为 px 的工具类
*
* @author blue
*
*/
public class DisplayUtil
{
/**
* 将px值转换为dip或dp值,保证尺寸大小不变
*
* @param context
* @param pxValue
* @return
*/
public static int px2dip(Context context, float pxValue)
{
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
/**
* 将dip或dp值转换为px值,保证尺寸大小不变
*
* @param context
* @param dipValue
* (DisplayMetrics类中属性density)
* @return
*/
public static int dip2px(Context context, float dipValue)
{
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
/**
* 将px值转换为sp值,保证文字大小不变
*
* @param context
* @param pxValue
* @return
*/
public static int px2sp(Context context, float pxValue)
{
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (pxValue / fontScale + 0.5f);
}
/**
* 将sp值转换为px值,保证文字大小不变
*
* @param context
* @param spValue
* @return
*/
public static int sp2px(Context context, float spValue)
{
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
}