实现手指点击和触摸移动时,图片跟随移动,想象成简陋的坦克大战即可
直接上代码:
第一步:先自定义一个View类,用作绘制View
public class MoveView extends View {
private Bitmap bitmap;
private float planeX=1f;
private float planeY=1f;
public Paint paint = new Paint();
public MoveView(Context context) {
super(context);
}
public MoveView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
paint.setColor(Color.BLUE);
paint.setAntiAlias(true);
paint.setDither(true);
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.tanke);//通过使用bitmapfactory的decoderesource来获得bitmap
}
public MoveView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//canvas.drawCircle(planeX, planeY, 20, paint);//也可以直接绘制一个圆
canvas.drawBitmap(bitmap,planeX-bitmap.getWidth()/2,planeY-bitmap.getHeight()/2,paint);
}
//接收位置信息
public void setPlane(float x,float y) {
planeX=x;
planeY=y;
}
}
第二步:写布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_info"
android:text="坐标:xxx,xxx"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<com.example.lp.mydraw.MyView.MoveView
android:id="@+id/mv_move"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
</LinearLayout>

第三步:编写Activity,重写onTouchEvent来执行触摸操作,并将触摸操作传递到自定义的view中,绘制图形。
public class MainActivity extends AppCompatActivity {
private MoveView moveView;
private TextView locationInfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
moveView=findViewById(R.id.mv_move);
locationInfo=findViewById(R.id.tv_info);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置全屏
}
@Override
public boolean onTouchEvent(final MotionEvent event) {
locationInfo.setText("当前坐标\n"+event.getX()+" , "+event.getY());
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
moveView.setPlane(event.getX(),event.getY());
moveView.invalidate();
break;
case MotionEvent.ACTION_MOVE:
moveView.setPlane(event.getX(),event.getY());
moveView.invalidate();
break;
}
return super.onTouchEvent(event);
}
}
资源图片:tanke.png

大功告成。
demo连接:https://github.com/CodeLpea/PracticceOfAndorid.git

谢谢大家。
网友评论