android小Demo--圓球跟隨手指軌跡移動

  eatwhatApp的客戶端基本實現,會再後續進行整改,今天作一個在網上找到的小Demo,讓屏幕中出現一個圓球,並跟隨手指移動。

  寫個java類DrawView繼承於View:

public class DrawView extends View {

	public DrawView(Context context) {
		super(context);
	}
}

  定義屬性:

	//畫筆
	private Paint paint;
	//當前X座標
	private float currentX;
	//當前Y座標
	private float currentY;

	public DrawView(Context context) {
		super(context);
		this.paint = new Paint();
		this.currentX = 100;
		this.currentY = 100;
	}

  重寫onDraw()方法:

        @Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
            	//設置畫筆顏色
		paint.setColor(Color.RED);
		//繪製圓形,中心位置(currentX, currentY),半徑10
		canvas.drawCircle(currentX, currentY, 10, paint);
	}     

  重寫onTouchEven()方法:

        @Override
    public boolean onTouchEvent(MotionEvent event) {
        
        //獲取點擊事件的座標x,y
        currentX = event.getX();
        currentY = event.getY();
        
        //重繪控件
        invalidate();
        return true;
    }        

 

  以後變能夠在activity中實例化該控件:

        RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout);
        DrawView draw = new DrawView(this);
        layout.addView(draw);

 

  這樣便完成了該demo。

相關文章
相關標籤/搜索