Android实现随手指移动小球
导读
本文实例为大家分享了Android实现随手指移动小球的具体代码,供大家参考,具体内容如下
这个随手指移动小球,首先要使用paint画笔在canvas画布画出一个圆,然后重写OnTouchEvent(),进行小球的坐标的获取和小球的重新绘画。
package com.bwei.self_view; 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 ZhangTAO on 2017/11/2. */ public class MyView extends View{ // 初始化圆的位置 public int x = 200; public int y = 600; Context context; public MyView(Context context) { super(context,null); this.context = context; } public MyView(Context context, @Nullable AttributeSet attrs) { super(context, attrs,0); this.context = context; } public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(); this.context = context; } private void initView() { setBackgroundColor(Color.BLUE); } /** * @canvas 画布 paint 画笔 */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //建立一根画笔 Paint paint = new Paint(); paint.setStyle(Paint.Style.FILL); paint.setColor(Color.RED); paint.setFakeBoldText(true); //画布 canvas.drawCircle(DipUtils.dip(getContext(),x), DipUtils.dip(getContext(),y), DipUtils.dip(getContext(),50),paint); } /** * 进行设置touch移动 */ @Override public boolean onTouchEvent(MotionEvent event) { super.onTouchEvent(event); int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN : case MotionEvent.ACTION_MOVE : case MotionEvent.ACTION_UP : //获取当前触摸点的x,y坐标 x = (int) event.getX(); y = (int) event.getY(); invalidate(); break; } // 获取屏幕的宽高 WindowManager manger = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); int width = manger.getDefaultDisplay().getWidth(); int height = manger.getDefaultDisplay().getHeight(); //重新绘制圆 ,控制小球不会被移除屏幕 if(x>=20 && y>=20 && x<=width-20 && y<height-20) { invalidate(); } //自己处理触摸事件 return true; //修改当前的坐标 // this.x =(int) event.getX(); // this.y =(int) event.getY(); //重绘小球 // this.invalidate(); // return true; } }
效果图:
评论(0)