1.画圆类
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
/**
*
**/
public class DrawCircle extends View {
private Paint paint;
private float x=300,y=300,oy,ox;
public DrawCircle(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint=new Paint();
paint.setColor(Color.RED);
paint.setAntiAlias(true);//画笔设置抗拒是
canvas.drawCircle(x,y,80,paint);//画圆
ox=x;
oy=y;
}
public void setXY(float q,float w){
this.x=q;
this.y=w;
invalidate();//刷新
}
public Float[] getOldValues(){
return new Float[]{ox,oy};
}
}
2.activity
package com.example.catchme;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private int w,h;
private DrawCircle drawCircle;
private RelativeLayout layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WindowManager wm= (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
//屏幕的宽和高
w=wm.getDefaultDisplay().getWidth();
h=wm.getDefaultDisplay().getHeight();
layout=(RelativeLayout) findViewById(R.id.layouymain);
drawCircle=new DrawCircle(this);
drawCircle.setMinimumWidth(w);
drawCircle.setMinimumHeight(h);
drawCircle.invalidate();//刷新
drawCircle.setBackgroundResource(R.mipmap.ic_launcher_round);//设置背景
layout.addView(drawCircle);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// MotionEvent.ACTION_DOWN手势落下
if(MotionEvent.ACTION_DOWN==event.getAction()){
float x=event.getX();
float y=event.getY();
//判断 手指点的是否在园内
if(drawCircle.getOldValues()[0]+80>x&&drawCircle.getOldValues()[0]-80<=x&&drawCircle.getOldValues()[1]+80>y&&drawCircle.getOldValues()[1]-80<=y
){
Random random=new Random();
int sendX,sendY;
do {
sendX=random.nextInt((w-80));
sendY=random.nextInt((h-80));
}while (sendX<80&&sendY<200&&(drawCircle.getOldValues()[1]+80)>sendX&&sendY>(drawCircle.getOldValues()[1]+80));
drawCircle.setXY(sendX,sendY);
}
}
return super.onTouchEvent(event);
}
public void onlcbtn(View view){
}
}
3.界面
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/layouymain"
>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="开始抓"
android:onClick="onlcbtn"
></Button>
</RelativeLayout>