zoukankan      html  css  js  c++  java
  • Android中dp和px之间进行转换

    引用:http://blog.csdn.net/arui319/article/details/6777133

    http://blog.csdn.net/eggcalm/article/details/7006378

    在xml布局文件中,我们既可以设置px,也可以设置dp(或者dip)。一般情况下,我们都会选择使用dp,这样可以保证不同屏幕分辨率的机器上布局一致。但是在代码中,如何处理呢?很多控件的方法中都只提供了设置px的方法,例如setPadding,并没有提供设置dp的方法。这个时候,如果需要设置dp的话,就要将dp转换成px了。

    以下是一个应用类,方便进行px和dp之间的转换。

    1. import android.content.Context;  
    2.   
    3. public class DensityUtil {  
    4.   
    5.     /** 
    6.      * 根据手机的分辨率从 dp 的单位 转成为 px(像素) 
    7.      */  
    8.     public static int dip2px(Context context, float dpValue) {  
    9.         final float scale = context.getResources().getDisplayMetrics().density;  
    10.         return (int) (dpValue * scale + 0.5f);  
    11.     }  
    12.   
    13.     /** 
    14.      * 根据手机的分辨率从 px(像素) 的单位 转成为 dp 
    15.      */  
    16.     public static int px2dip(Context context, float pxValue) {  
    17.         final float scale = context.getResources().getDisplayMetrics().density;  
    18.         return (int) (pxValue / scale + 0.5f);  
    19.     }  
    20. }  

    ---------------------------------------------------------------------------

    GL(arui319)

    http://blog.csdn.net/arui319

    <本文可以转载,但是请保留以上作者信息。谢谢。>

    ---------------------------------------------------------------------------

  • 相关阅读:
    Eureka 原理圖
    RabbitMQ 介紹
    rabbitmq-3.5.1-安裝
    MyBatis 基础入门
    CSS
    程序员必会算法-KMP算法
    编程这些年
    排序算法之直接插入排序
    排序算法之选择排序
    排序算法之冒泡排序
  • 原文地址:https://www.cnblogs.com/sode/p/2938286.html
Copyright © 2011-2022 走看看