自定义View实现拖动小圆球,并随机改变其颜色
//简单实现
package com.example.demo1;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import java.util.Random;
/**
@Author:lenovo
@E-mail: **********@163.com
@Date:2019/5/27 20:13
@Description:描述信息
*/
public class MyView extends View {
//画笔
private Paint mPaint;
//圆的半径
private float mRadius = 50f;
//圆的圆心的x坐标
public float pointX = mRadius;
//圆的圆心的Y坐标
public float pointY = mRadius;
//控制是否可以移动的变量 true的时候可以移动
private boolean moveable;
//定义颜色数组
private int colorArray[] = {Color.BLACK,Color.BLACK,Color.GREEN,Color.YELLOW, Color.RED};
private int paintColor = colorArray[0]; //定义画笔默认颜色
Context context;
public MyView(Context context) {
super(context);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
//创建画笔
mPaint = new Paint();
//随机设置画笔颜色
mPaint.setColor(paintColor);
//mPaint.setStyle(Paint.Style.STROKE); //绘制空心圆
}
public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
setPaintRandomColor();
//根据圆心的坐标来绘制圆的位置的
canvas.drawCircle(pointX, pointY, mRadius, mPaint);
//线,我们根据圆心的位置上下左右画了四条超出屏幕的线(跟瞄准镜似得~手动滑稽)
//我们是不是可以有别的想法?陀螺仪去把我们的瞄准镜调动起来
canvas.drawLine(pointX,pointY, pointX+1500,pointY,mPaint);
canvas.drawLine(pointX,pointY, pointX-1500,pointY,mPaint);
canvas.drawLine(pointX,pointY, pointX,pointY+2500,mPaint);
canvas.drawLine(pointX,pointY, pointX,pointY-2500,mPaint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//手指触摸的 X Y 轴的坐标
float touchX;
float touchY;
//判断事件的类型
switch (event.getAction()){
//按下的事件
case MotionEvent.ACTION_DOWN:
touchX = event.getX();
touchY = event.getY();
//触摸位置的判断
if(touchX > pointX - mRadius && touchX < pointX + mRadius && touchY > pointY - mRadius && touchY < pointY + mRadius){
moveable = true;
}else{
moveable = false;
}
break;
//移动的事件
case MotionEvent.ACTION_MOVE:
if(moveable){
// 把我们圆心的位置(pointX,pointY)设置成当前触摸的位置(event.getX(),event.getY())
pointX = event.getX();
pointY = event.getY();
//重新绘制(重新调取onDraw方法)
invalidate();
}
break;
//抬起
case MotionEvent.ACTION_UP:
break;
}
/*
此处一定要将return super.onTouchEvent(event)修改为return true,原因是:
父类的onTouchEvent(event)方法可能没有做任何处理,但是返回了false。
一旦返回false,在该方法中再也不会收到MotionEvent.ACTION_MOVE及MotionEvent.ACTION_UP事件。
*/
return true;
}
//为画笔设置随机颜色的方法
private void setPaintRandomColor(){
Random rand = new Random();
int randomIndex = rand.nextInt(colorArray.length);
mPaint.setColor(colorArray[randomIndex]);
}
}
这里是布局
<com.example.demo1.MyView
android:id="@+id/my_view"
android:layout_width=“match_parent”
android:layout_height=“match_parent”
/>
---------------------