Android自定义View通过触摸事件移动View的位置

1、上图给吃瓜群众

这个安卓小机器人是可以通过触摸屏幕而跟着你手指动的!!

2、Demo基本设计思路
2.1、自定义一个GameView继承自View;
2.2、在View上绘制一个Bitmap对象,后续会通过触摸事件来改变该图的位置;
2.3、监听Activity的onTouchEvent事件,将事件发生的坐标传递给自定义View;
2.4、自定义View中通过接收到的坐标位置,实时改变Bitmap所处的位置,实现类型移动某对象的功能;

3、关键代码
3.1、自定义View:GameView

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.yusian.event.game;
 
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;
 
/**
 * Created by Sian on 2017/3/8.
 */
 
public class GameView extends View {
 
    Bitmap bitmap = null;
    private float bitmapX, bitmapY;
 
    public void setBitmapPoint(float x, float y){
        this.bitmapX = x;
        this.bitmapY = y;
        // 使用View的invalidate()方法刷新页面,使之调用onDraw()方法
        this.invalidate();
    }
 
    // 希望在XML布局文件中添加控件,实现该构造方法
    public GameView(Context context, AttributeSet attrs){
        super(context, attrs);
        // 取出图片id
        int id = com.yusian.event.R.mipmap.ic_launcher;
        // 使用BitmapFactory的静态方法decodeResoure()生成Bitmap图片
        // view的getResource()方法可取到当前资料包
        bitmap = BitmapFactory.decodeResource(getResources(), id);
    }
 
    @Override
    // 页面创建或被刷新时被调用
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 画布上绘制一个位图
        canvas.drawBitmap(bitmap, bitmapX, bitmapY, null);
    }
}

3.2、XML

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.yusian.event.MainActivity">
 
    <com.yusian.event.game.GameView
        android:id="@+id/gameView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
 
</LinearLayout>

3.3、Activity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.yusian.event;
 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
 
import com.yusian.event.game.GameView;
 
public class MainActivity extends AppCompatActivity {
    GameView gameView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        gameView = (GameView)findViewById(R.id.gameView);
    }
 
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY() - 250;
        this.gameView.setBitmapPoint(x, y);
        return super.onTouchEvent(event);
    }
}

Leave a Reply