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 @Override 17 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.xml
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="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 @Override 10 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 @Override 23 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 }
时间: 2024-10-18 06:18:48