dp和px的转化



 

一、首先要认识下:屏幕密度ppi
ppi  pixles percent inch  每英寸的像素数
ppi = 水平方向的像素数 / 屏幕宽度

例如:3.7in   480 x 800
         3.7 * 3.7 = 3x*3x + 5x * 5x 
宽度: 3 * 0.63 = 1.89   
PPI ?  480 / 1.89 = 254

规定:ppi是160,标准屏幕密度   mdpi
          240    hdpi
         
二、dp和px的转化
dp和px换算公式:   1dp = 当前屏幕密度 / 160 * 1px
3.7in   480 x 800    1dp = 1.5px


三、代码实现
package com.nooice.library.utils;

import android.content.Context;

/**
 * @describe <dp和px的转化>
 */
public class RKDensityUtil {
 
 public static int dpToPx(Context context,float dpValue) {//dp转换为px
  float scale=context.getResources().getDisplayMetrics().density;//获得当前屏幕密度
  return (int)(dpValue*scale+0.5f);  
 }
 
 public static int pxToDp(Context context,float pxValue) {//px转换为dp
  float scale=context.getResources().getDisplayMetrics().density;//获得当前屏幕密度
  return (int)(pxValue/scale+0.5f);  
 }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值