您的位置:首页 > 其它

自定义View_绘制圆_进行拖动(不出屏幕)放大缩小

2017-04-16 21:13 399 查看
package com.example.administrator.week_2_demo;

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;

/**
* Created by Administrator on 2017/4/16.
*/
public class MyView extends View {
private float vx=100;
private float vy=100;
private float vr=50;
private float distance;
private int width;
private int height;
private final float increment = 10;
private final float min = 50;
public MyView(Context context) {
super(context);
}

public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}

public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.FILL);
canvas.drawCircle(vx, vy, vr, paint);
width = getWidth();
height = getHeight();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//手指的数量
int count = event.getPointerCount();
float x = event.getX();
float y = event.getY();
int action = event.getAction();
if(action==MotionEvent.ACTION_POINTER_DOWN){
distance = getDistance(event);
}
if(count==1) {
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_MOVE) {
if (x > width - vr) {
vx = width - vr;
} else if (x < vr) {
vx = vr;
} else {
vx = x;
}
if (y > height - vr) {
vy = height - vr;
} else if (y < vr) {
vy = vr;
} else {
vy = y;
}
postInvalidate();
}
}
else if(count==2&&action == MotionEvent.ACTION_MOVE){

float maxR = 0;

if(vx<vy){
maxR = vx;
}else{
maxR = vy;
}

//判断手指方向
if(distance>getDistance(event)){
vr -= increment;
if(vr<min){
vr = min;
}
}else if(distance<getDistance(event)){
vr += increment;
if(vr>maxR){
vr = maxR;
}else if(vr>width/2){
vr = width/2;
}
}
distance = getDistance(event);
postInvalidate();
}
return true;
}
private float getDistance(MotionEvent event){

float xOne = event.getX(0);
float yOne = event.getY(0);
float xTwo = event.getX(1);
float yTwo = event.getY(1);
return (xOne - xTwo)*(xOne - xTwo)+(yOne - yTwo)*(yOne - yTwo);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐