Android 进阶之 View 的绘制(一)

基础知识

1. View 类简介

  • View 类是 Android 中各种组件的基类,如:View 是 ViewGroup 基类。
  • View 的构造函数:
View(Context)
 
View(Context, AttributeSet)
 
View(Context, AttributeSet, defStyleAttr)
 
View(Context, AttributeSet, defStyleAttr, defStyleRes)

附:
深入理解View的构造函数
理解View的构造函数

2. View 视图结构

树形结构

记住: 无论是 measure 过程、layout 过程还是 draw 过程,永远都是从 View 树的根节点开始测量或计算(即从树的顶端开始),一层一层、一个分支一个分支地进行(即树形递归),最终计算整个 View 树中各个 View,最终确定整个 View 树的相关属性。

3. View 位置描述

image

View的位置由 4 个顶点决定的,4 个顶点的位置描述分别由4个值决定:

  • Top:子 View 上边界到父 View 上边界的距离
  • Left:子 View 左边界到父 View 左边界的距离
  • Bottom:子 View 下边距到父 View 上边界的距离
  • Right:子 View 右边界到父 View 左边界的距离

4. 位置获取方式

  • View 的位置是通过 view.getxxx() 函数进行获取:(以Top为例)
// 获取Top位置
public final int getTop() {  
    return mTop;  
}  
  • 与 MotionEvent 中 get() 和 getRaw() 的区别
//get() :触摸点相对于其所在组件坐标系的坐标
 event.getX();       
 event.getY();

//getRaw() :触摸点相对于屏幕默认坐标系的坐标
 event.getRawX();    
 event.getRawY();

5. Android 相关

1). 坐标系
Android 的坐标系定义为:
- 屏幕的左上角为坐标原点
- 向右为 x 轴增大方向
- 向下为 y 轴增大方向
具体如下图:
image

2). 颜色

  • 定义颜色的方式
    a. 在 Java 中定义颜色
/java中使用 Color 类定义颜色
 int color = Color.GRAY;     //灰色

  //Color类是使用ARGB值进行表示
  int color = Color.argb(127, 255, 0, 0);   //半透明红色
  int color = 0xaaff0000;                   //带有透明度的红色

b. 在 xml 文件中定义颜色

<?xml version="1.0" encoding="utf-8"?>
<resources>

    //定义了红色(没有alpha(透明)通道)
    <color name="red">#ff0000</color>
    //定义了蓝色(没有alpha(透明)通道)
    <color name="green">#00ff00</color>
</resources>
  • 引用颜色的方式
    a. 在 Java 中引用 xml 中定义的颜色:
/方法1
int color = getResources().getColor(R.color.mycolor);

//方法2(API 23及以上)
int color = getColor(R.color.myColor); 

b. 在 xml 文件( layout 或 style)中引用或者创建颜色

<!--在style文件中引用-->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/red</item>
    </style>

 <!--在layout文件中引用在/res/values/color.xml中定义的颜色-->
  android:background="@color/red"     

 <!--在layout文件中创建并使用颜色-->
  android:background="#ff0000"     
发布了225 篇原创文章 · 获赞 64 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/duoduo_11011/article/details/103882649