绘制当前触控操作,自定义View(画随指动)

实现手指点击和触摸移动时,图片跟随移动,想象成简陋的坦克大战即可

直接上代码:
第一步:先自定义一个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;

    }
}

第二步:写布局文件



    
        
        

    




image.png

第三步:编写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


tanke.png

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

image.png

谢谢大家。

你可能感兴趣的:(绘制当前触控操作,自定义View(画随指动))