draw是繪製View三個步驟中的最後一步。同measure、layout同樣,一般不對draw自己進行重寫,draw內部會調用onDraw方法,子類View須要重寫onDraw(Canvas),以完成最終的繪製。java
若是必定要重寫draw(Canvas)的話,須要在方法的開始處調用super.draw(canvas)。android
draw內部具體作了什麼事情,在View.java的源碼註釋中已經作了很是詳細的介紹canvas
/* * Draw traversal performs several drawing steps which must be executed * in the appropriate order: * * 1. Draw the background * 2. If necessary, save the canvas' layers to prepare for fading * 3. Draw view's content * 4. Draw children * 5. If necessary, draw the fading edges and restore layers * 6. Draw decorations (scrollbars for instance) */
draw這個過程,在目前的階段能講的東西並很少。若是深刻到具體一個SDK已經實現的View內部去看代碼,夠我吃一大壺的了——單單是最經常使用的TextView,它的onDraw就很是複雜。app
這裏本身實現一個很是簡單的Custom View——在一塊背景色上顯示一行文字。先來看一下完成後的頁面截圖:ide
是否是很是簡單?下面是自定義的ThreeBodyView.javaspa
public class ThreeBodyiView extends View { private Paint mPaint; private String mText; public ThreeBodyiView(Context context, AttributeSet attrs) { super(context, attrs); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mText = "nothing to show..."; } @Override protected void onDraw(Canvas canvas) { mPaint.setColor(Color.GREEN); // 背景色 canvas.drawRect(0, 0, getWidth(), getHeight(), mPaint); mPaint.setColor(Color.RED); mPaint.setTextSize(100); // 文字顏色、大小 canvas.drawText(mText, 0, getHeight() / 2, mPaint); } public void setText (String s) { mText = s; super.invalidate(); } }
ThreeBodyView.java在一塊矩形區域裏顯示了一行文字,能夠經過setText(String)方法來動態改變所顯示的文字。3d
在使用的時候,是這樣用的:rest
fake_main_activity.xmlcode
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/fake_main_layout" android:layout_width="match_parent" android:layout_height="match_parent" > <com.leili.imhere.view.ThreeBodyiView android:id="@+id/three_body_view" android:layout_width="300dp" android:layout_height="300dp" /> </FrameLayout>
FakeMainActivity.javaorm
public class FakeMainActivity extends Activity { private ThreeBodyiView tbView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.fake_main_activity); tbView = (ThreeBodyiView) super.findViewById(R.id.three_body_view); tbView.setText("世界屬於三體!"); } }
分析了draw的過程,在講解onDraw時,佐以一個簡單的demo,demo中實現一個弱化的TextView。
下一篇是本系列的完結篇,會作一個較完整的自定義View/ViewGroup。