android view绘制流程解析

首先需要了解几个概念:

Activity:基本页面单元 Activity包含一个Window 上面可以绘制各种view

view:最基本ui组件 表示屏幕上的一个矩形区域

Window:表示顶层窗口 管理界面的显示和事件的响应 每一个activity都会创建一个

PhoneWindow对象:是activity和整个view系统交互的接口

phonewindow类继承于window类 同事phonewindow类内部包含了一个DecorVie对象 

相当于phoneWindow是把一个FrameLayout进行了一定的包装 并提供了一组通用的窗口操作接口

DecorView:是window中view的rootview设置窗口属性 是FrameLayout的子类

并且是PhoneWindow的一个内部类 DecorView(修饰类)就是对普通的FrameLayout进行了一定的修饰

比如添加一个通用的titlebar并且响应特定的按键消息

ViewRoot:并不是一个view类型 而是一个Handler

主要作用: 

向DecorView分发收到的用户发起的event事件 按键 触屏等事件

与windowmanagerservice交互 完成整个Activity 的gui绘制



整个view的绘制流程是在viewroot类的performTraversals()函数展开的 执行过程:

根据之前设置的转台 判断是否需要重新计算视图大小 measure 是否需要重新安置视图的位置layout

以及是否需要重新绘制draw


自定义ViewGroup

public class MyViewGroup extends ViewGroup{

public MyViewGroup(Context context){}

public MyViewGroup(Context context,AttributeSet attr){}

onMeasure(int widthMeasureSpec, int heightMeasureSpe){

int childCount = getchildCount();

//获取ViewGroup实际的宽度和长度 涉及到MeasureSpec类的使用

int specWidth = MeasureSpec.getSize(widthMeasureSpec);

int specHeight = MeasureSpec.getSize(heigthMeasureSpe);

//设置本ViewGroup宽高、

setMeasureDimension(specWidth,specHeigth);

//设置每一个子view

for(int i=0;i<childCount;i++){

View child = getChildAt(i);

child.measure(80,80);//设置宽高

}

onLayout(boolean changed,int l,int t,int r,int b){

int childCount = getChildCount();

int startLeft= 0;

int startTop =10;

for(int i=0;iKchildCount;i++){

View child = getChildAt(i);//获得每一个对象引用

child.layout(l,t,r,b);

startLeft =startLeft+child.getMeasuredWidth() + 10;  //校准startLeft值,View之间的间距设为10px ;              

}

}

dispatchDraw(Canvas canvas){}

drawChild(Canvas can,View child,long drawtime);


}

}

自定义View类型 MyView 重写onDraw()方法

public class MyView extends View{

private Paint paint = new Paint();

MyView(Context context){}

protected void onMeasure(int width,int height){

//设置view大小

setMeasureDimension(80,80);

}

//存在canvas对象 存在默然显示区域

onDraw(Canvas canvas){

paint.setColor(Color.RED);

canvas.drawColor(Color.BLUE);//view的背景色

canvas.drawRect(0.0,30,30,paint);//绘制矩形

canvas.drawText("MyView",10,40,paint);

}


}

详情请参照:点击打开链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值