依次顯示自定義圖形。
一:定義一個類繼承View基類,重寫View基類的方法,定義自己要畫出的圖形。
1:自定義圓形
public class Round extends View{
Paint p = new Paint();
public Round(Context context){
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
p.setColor(Color. RED);
canvas.drawCircle(300,100,100, p);
}
}
2:自定義一個正方形
public class Square extends View{
Paint p=new Paint();
Rect r=new Rect(200, 300, 400, 500);
public Square (Context context){
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
p.setColor(Color. BLUE);
canvas.drawRect( r, p);
}
}
二:在MainActivity主函數中,用多態知識實現依次畫出不同的圖形。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RelativeLayout root = new RelativeLayout(this);
setContentView(root);
// 實例化要畫出的圖形
Round round = new Round(this );
Square square = new Square(this );
// 將要畫出圖形的實例放到數組中
View[] v = new View[] { round, square };
// 遍歷數組,將圖形對象放到佈局文件中
for (int i = 0; i < v.length; i++) {
root.addView(v[i]);
}
}
在主函數中,將要畫出圖形的實例放到View類型的數組中,遍歷數組顯示圖形。
下面是效果圖: