除了在XML中使用Shape Drawable 資源外(如上例),也可以使用代碼來定義Shape Drawable,為Android中定義的Shape 類層次圖:
如果熟悉二維圖形開發,Path, Arc, Rect, Oval, RoundRect應該不陌生。 本例ShapeDrawable使用代碼來建立各種ShapeDrawable 並自訂一個Shape :MyShapeDrawable.
Android 中的 Shader 類同於其它平台的畫刷Brush (可以由單色畫刷,線性漸層畫刷,材質bitmap畫刷等)。
ShapeDrawable 中的幾個例子,只有第四個RoundRect 有些奇形怪狀。這是因為繪製這個RoundRectShape的Paint 使用了PathEffect:
[java]
PathEffect pe = new DiscretePathEffect(10, 4);
PathEffect pe2 = new CornerPathEffect(4);
mDrawables[3].getPaint().setPathEffect(
new ComposePathEffect(pe2, pe));
PathEffect pe = new DiscretePathEffect(10, 4);
PathEffect pe2 = new CornerPathEffect(4);
mDrawables[3].getPaint().setPathEffect(
new ComposePathEffect(pe2, pe));
PathEffect 可以影響Paint繪製圖形時幾何形體的形狀,Android提供了ComposePathEffect ,ConerPathEffect, DashPathEffec, DiscretePathEffect, PathDashPathEffect, SumPathEffect等幾種PathEffect。其中DiscretePathEffect可以隨機的位移原路徑位置,才有了本例的效果。
作者:mapdigit