package com.wuxinle.touchimageview.utils;
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;
/**
* @author: ding xujun
* @created on: 2019/3/25 11:12
* @project: TouchImageView-master
*/
public class DrawView1 extends View {
private Context context;
private int x = 100;
private int y = 100;
private int radius = 100;
private Paint mpaint;
private int width;
private int height;
public DrawView1(Context context) {
super(context);
this.context = context;
init();
}
public DrawView1(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public DrawView1(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(x, y, radius, mpaint);
System.out.println("---------canvas");
}
private void init() {
mpaint = new Paint();
mpaint.setColor(Color.RED);
mpaint.setAntiAlias(true);
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
width = manager.getDefaultDisplay().getWidth();
height = manager.getDefaultDisplay().getHeight();
}
private int lastx;
private int lastY;
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
x = (int) event.getX();
y = (int) event.getY();
if (x >= 100 && y >= 100 && x <= width - 100 && y <= height - 300) {
if (Math.abs(x - lastx) <= 200 && Math.abs(y - lastY) <= 200) {
postInvalidate();
lastx = x;
lastY = y;
}
}
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
使用:
package com.wuxinle.touchimageview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.wuxinle.touchimageview.utils.DrawView1;
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DrawView1 drawView1 =new DrawView1(getBaseContext());
setContentView(drawView1);
}
}
标签:DrawView1,自定义,拖动,private,int,context,import,android,View
来源: https://blog.csdn.net/qq_35956194/article/details/88846153