zoukankan      html  css  js  c++  java
  • px与dp、sp之间的转换

    我们在安卓开发时,往往需要在java代码中动态设置某个控件的大小(宽度和高度等),那么这个时候你会发现,设置的结果单位是px,但是我们还是想要dp或者sp,那这时候我们就得自己计算了。

    下面是写好的帮助类,直接就可以去设置单位之间的转换:

     1 import android.content.Context;
     2 
     3 /**
     4  * Created by ws on 2016/3/4.
     5  */
     6 public class DisPlayUtil {
     7     /**
     8      * 将px值转换为dip或dp值,保证尺寸大小不变
     9      */
    10     public static int px2dip(Context context, float pxValue) {
    11         final float scale = context.getResources().getDisplayMetrics().density;
    12         return (int) (pxValue / scale + 0.5f);
    13     }
    14 
    15     /**
    16      * 将dip或dp值转换为px值,保证尺寸大小不变
    17      */
    18     public static int dip2px(Context context, float dipValue) {
    19         final float scale = context.getResources().getDisplayMetrics().density;
    20         return (int) (dipValue * scale + 0.5f);
    21     }
    22 
    23     /**
    24      * 将px值转换为sp值,保证文字大小不变
    25      */
    26     public static int px2sp(Context context, float pxValue) {
    27         final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
    28         return (int) (pxValue / fontScale + 0.5f);
    29     }
    30 
    31     /**
    32      * 将sp值转换为px值,保证文字大小不变
    33      */
    34     public static int sp2px(Context context, float spValue) {
    35         final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
    36         return (int) (spValue * fontScale + 0.5f);
    37     }
    38 }

    帮助类很简单,只是还需要传一个参数Context,那么谁调用他,就把谁作为参数传递到方法中,因为这里需要当前调用者的上下文场景。

    小知识点需要日积月累(by四海小森森)

  • 相关阅读:
    错删表空间的恢复步骤
    如何使用PL/SQL进行远程数据库连接
    Oracle基础笔记
    PL/SQL如何导入dmp文件
    oracle表的基本操作
    sql里面的分页
    truncate table语句和delete table语句的区别
    c++ 时间类型详解 time_t[转]
    C++ 容器:顺序性容器、关联式容器和容器适配器
    XCode 快捷键
  • 原文地址:https://www.cnblogs.com/ccshxt/p/5245017.html
Copyright © 2011-2022 走看看