001-关于Android的一些基础详解【五年Android从0复盘系列】

356 阅读1分钟

1.像素相关

1.1 Android支持的像素单位:

1. px 像素
2. in 英寸
3. mm 毫米
4. pt 磅 ( 1/72英寸 )
5. dp ( dip )与设备无关的显示单位
6. sp 设置字体大小

1.2 Android常用的单位

1. dp 显示单位 ,设置字体时,【不会】随系统字体大小设置变化
2. sp 字体单位,设置字体【会】随系统字体大小设置变化
3. px 设备实际像素单位

1.3 dp与px单位转换

    实际使用
            1. xml 中  除了sp用于设置文字大小,其余地方用dp
            2. java代码中 java方法都是以px为计算单位,dp数字需提前转换成px
    /** 
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)  。
     */  
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);//+0.5f原因:转int时,曲线实现四舍五入
    }
    /** 
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp 。
     */  
    public static int px2dip(Context context, float pxValue) {
        //density指的是像素密度,即一个单位内有几个像素
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
//==========设备屏幕========================
     /**
     * 获取设备宽度(px)
     */
    public static int deviceWidth(Context context) {
        //widthPixels和heightPixels的单位都是像素
        return context.getResources().getDisplayMetrics().widthPixels;
    }
    /**
     * 获取设备宽度【dp】<===
     */
    public static int deviceWidthDp(Context context) {
        return px2dp(context , deviceWidth(context));
    }
    /**
     * 获取设备高度(px)
     */
    public static int deviceHeight(Context context) {
        //widthPixels和heightPixels的单位都是像素
        return context.getResources().getDisplayMetrics().heightPixels;
    }
    /**
     * 获取设备高度【dp】<===
     */
    public static int deviceHeightDp(Context context) {
        return px2dp(context ,deviceHeight(context));
    }

2. 颜色相关

2.1 两种编码格式

ARGB :#ff00aa99

    第一二位:透明值,00为全透明,ff为不透明,其他值为对应透明度 :
                    ( 透明值/256)*100%;
    第三四位:红色值,( 红色值/256)*100% ,ff表示纯红;
    第五六位:绿色值,( 绿色值/256)*100% ,ff表示纯绿;
    第七八位:蓝色值,( 蓝色值/256)*100% ,ff表示纯蓝;

RGB :#00AA88

    第一二位:红色值;
    第三四位:绿色值;
    第五六为:蓝色值。

2.2 使用场景

xml布局文件

<!--  -->
android:textColor="#FF6699"

java代码设置颜色 java代码中不用六位编码,六位编码在代码中默认透明

//1.直接 设置 八位的【十六进制数值】
setTextColor(0xff00ff00);
//2.十进制设置 参数值[0,255]
Color.rgb(255, 0, 0);//红色
//Color.rgb(int red, int green, int blue);
Color.argb(127,0,255,0);//半透明绿色
//Color.argb(int alpha,int red, int green, int blue);
//3.获取xml颜色资源
setTextColor(getResources().getColor(R.color.diy_black_333333));