首先是介紹一下是怎麼畫圖!
有兩個類Canvas,Paint;
Canvas代表了“依附”了指定View的畫布,Paint 代表了Canvas上的畫筆;
如何在Android應用中繪制基本的集合圖形,關鍵在於一個自定義View組件,要重寫View組件的onDraw(Canvase)方法,接下來是在該 Canvas上繪制大量的幾何圖形,球形,方塊,線,等各種形狀!
畫球: Canvas.drawCircle(x,y,len,paint)
為球綁上Touch事件;
原碼如下:
CustomView類:
- public void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- //獲取布局文件中的LinearLayout容器
- LinearLayout root = (LinearLayout)findViewById(R.id.root);
- //創建DrawView組件
- final DrawView draw =new DrawView(this);
- //設置自定義組件的最大寬度、高度
- draw.setMinimumWidth(300);
- draw.setMinimumHeight(500);
- //為draw組件綁定Touch事件
- draw.setOnTouchListener(new OnTouchListener()
- {
- @Override
- public boolean onTouch(View arg0, MotionEvent event)
- {
- //修改draw組件的currentX、currentY兩個屬性
- draw.currentX = event.getX();
- draw.currentY = event.getY();
- //通知draw組件重繪
- draw.invalidate();
- //返回true表明處理方法已經處理該事件
- return true;
- }
- });
- root.addView(draw);
- }
DrawView類:
-
- public float currentX = 40;
- public float currentY = 50;
- /**
- * @param context
- */
- public DrawView(Context context)
- {
- super(context);
- // TODO Auto-generatedconstructor stub
- }
- @Override
- public void onDraw (Canvas canvas)
- {
- super.onDraw(canvas);
- //創建畫筆
- Paint p = new Paint();
- //設置畫筆的顏色
- p.setColor(Color.GREEN);
- //繪制一個小圓(作為小球)
- canvas.drawCircle(currentX , currentY , 15 , p);
-
- }