Android_onDraw画圆与onTouchEvent方法处理触摸事件

一:布局




    



二:自定义类继承view

package activity.example.com.ballviewdemo;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;

/**
 * Created by 壹颗大金星 on 2017/11/2.
 */

public class BallView extends View{

    private int x = 100;
    private int y = 100;
    Context context;

    public BallView(Context context) {
        this(context,null);
        this.context=context;
    }

    public BallView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
        this.context=context;
    }

    public BallView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context=context;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 画笔
        Paint paint = new Paint();
        //设置画笔颜色
        paint.setColor(Color.RED);
        //绘制圆
        //cx :圆心的x坐标
        //cy :圆心的y坐标
        //radius :圆的半径
        //paint :画笔
        canvas.drawCircle(x, y, 50, paint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_UP:
                // 获取当前触摸点的x,y坐标
                x = (int) event.getX();
                y = (int) event.getY();
                break;
        }
        //获取屏幕宽高
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        int width = manager.getDefaultDisplay().getWidth();
        int heigh = manager.getDefaultDisplay().getHeight();
        //重新绘制圆 ,控制小球不会被移出屏幕
        if(x>=20 && y>=20 && x<=width-20 && y<=heigh-90){
            this.invalidate();
        }
        // 自己处理触摸事件
        return true;
    }
}


你可能感兴趣的:(Android_onDraw画圆与onTouchEvent方法处理触摸事件)