你的位置:首页 > 操作系统

[操作系统]跟随手指的小球


    

 

Crize_demo\draw_demo\src\main\java\com\ly\draw_demo\DrawView.java

 1 import android.content.Context; 2 import android.graphics.Canvas; 3 import android.graphics.Color; 4 import android.graphics.Paint; 5 import android.view.View; 6  7 public class DrawView extends View { 8  9   public float currentX = 40;10   public float currentY = 50;11 12   public DrawView(Context context) {13     super(context);14   }15 16   @Override17   protected void onDraw(Canvas canvas) {18     super.onDraw(canvas);19     //创建画笔20     Paint paint = new Paint();21     //设置画笔的颜色22     paint.setColor(Color.RED);23     //绘制一个小圆(作为小球)24     canvas.drawCircle(currentX,currentY,15,paint);25   }26 }

 

Crize_demo\draw_demo\src\main\res\layout\activity_main.

1 <LinearLayout ="http://schemas.android.com/apk/res/android"2   ="http://schemas.android.com/tools"3   android:layout_width="match_parent"4   android:layout_height="match_parent"5   android:orientation="horizontal"6   android:id="@+id/root"7   tools:context=".MainActivity">8 9 </LinearLayout>

 

Crize_demo\draw_demo\src\main\java\com\ly\draw_demo\MainActivity.java

 1 import android.app.Activity; 2 import android.os.Bundle; 3 import android.view.MotionEvent; 4 import android.view.View; 5 import android.widget.LinearLayout; 6  7 public class MainActivity extends Activity { 8    9   @Override10   protected void onCreate(Bundle savedInstanceState) {11     super.onCreate(savedInstanceState);12     setContentView(R.layout.activity_main);13     //获取布局文件中的LinearLayout容器14     LinearLayout root = (LinearLayout) findViewById(R.id.root);15     //创建DrawView组件16     final DrawView drawView = new DrawView(this);17     //设置自定义框架的宽度和高度18     drawView.setMinimumWidth(300);19     drawView.setMinimumHeight(500);20     //为drawView绑定Touch事件(触摸屏幕的监听事件)21     drawView.setOnTouchListener(new View.OnTouchListener() {22       @Override23       public boolean onTouch(View v, MotionEvent event) {24         //修改drawView组件的currentX,currentY两个属性25         drawView.currentX = event.getX();26         drawView.currentY = event.getY();27         //通知drawView组件重绘28         drawView.invalidate();29         //返回true表明处理方法已经处理该事件30         return true;31       }32     });33     root.addView(drawView);34   }35 36 37 }