android 屏幕显示

一、像素

android 常用单位 px、dp、sp

 

dp和sp只与屏幕的物理尺寸有关

dp和sp的区别: sp会随着系统字体的大小而改变,通常用来设置字体大小。dp不会随系统设置的字体改变

dp和px换算:设备的像素密度决定了dp和px的换算, 当密度为2时, 1pd=2px

在布局中,除了文字使用sp单位,其余部分一般使用dp作为单位,在代码中有些函数接收的是px单位。

 

    //设置内部文字与四周空间的间隔   
    textView.setPadding(px,px,px,px);

 

转换方法

    //分辨率dp转px
    public static int dp2px(Context context,float dpValue){
        //获取当前手机的像素密度
        final float scale=context.getResources().getDisplayMetrics().density;
        return (int)(dpValue*scale+0.5f);//四舍五入取整
    }
    //分辨率px转dp
    public static int px2dp(Context context,float pxValue){
        final float scale=context.getResources().getDisplayMetrics().density;
        return (int)(pxValue/scale+0.5f);
    }

 

二、颜色

1.系统自带颜色

 

2.自定义颜色

通常由8位 16进制数表示   alpha+RGB(RedGreenBlue)

8位的前两位表示透明度 0是完全透明,f表示完全不透明 ,三四位控制红色深度,五六位控制绿色深度,最后两位控制蓝色深度, 0-f由浅到深。

例如:

6位

0xffffff  表示黑色  0x00ff00表示绿色 

8位

0xff00ff00

6位编码看不到背景色。

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView tv1=findViewById(R.id.tv1);
        TextView tv2=findViewById(R.id.tv2);
        tv1.setBackgroundColor(0x00ff00);
        tv2.setBackgroundColor(0xff00ff00);
    }

 

 

 

在布局中,使用#RBG可以显示颜色

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:background="#00ff00">

或者

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:background="@color/colorGreen">

 

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorGreen">#00FF00</color>
</resources>

 代码中

 可以使用Color.rgb()或者Color.argb()方法

 

三、像素

        TextView tv=findViewById(R.id.tv1);
        int i=MainActivity.getScreenWidth(this);
        tv.setText(i+"");

 

1 获得容器宽度

    //获得屏幕宽度,单位px
    public static int getScreenWidth(Context context){
        //
        WindowManager wm= (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm=new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }

 

2.获得容器高度

dm.heightPixels;

 

3.获得像素密度

float类型
dm.density

4.

densityDpi

 

posted @ 2019-01-24 11:36  富坚老贼  阅读(231)  评论(0编辑  收藏  举报