怎样自定义一个UVCCameraTextureView类,使它支持多点触控可以放大缩小和旋转,onDraw不可重写
时间: 2023-11-28 20:49:16 浏览: 128
Android通过多点触控的方式对图片进行缩放的实例代码
要自定义一个支持多点触控的UVCCameraTextureView类,可以继承原有的UVCCameraTextureView类,并且在其中重写onTouchEvent方法,实现放大缩小和旋转功能。
以下代码给出了一个示例:
```
public class MyUVCCameraTextureView extends UVCCameraTextureView {
private static final int NONE = 0;
private static final int ROTATE = 1;
private static final int ZOOM = 2;
private int mode = NONE;
private PointF startPoint = new PointF();
private PointF midPoint = new PointF();
private float oldDist = 1f;
private float oldRotation = 0f;
public MyUVCCameraTextureView(Context context) {
super(context);
}
public MyUVCCameraTextureView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyUVCCameraTextureView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
startPoint.set(event.getX(), event.getY());
mode = ROTATE;
oldRotation = getRotation();
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = getDistance(event);
if (oldDist > 10f) {
midPoint = getMidPoint(event);
mode = ZOOM;
}
break;
case MotionEvent.ACTION_MOVE:
if (mode == ROTATE) {
float rotation = getRotation(event);
setRotation(oldRotation + rotation);
} else if (mode == ZOOM) {
float newDist = getDistance(event);
if (newDist > 10f) {
float scale = newDist / oldDist;
setScaleX(scale);
setScaleY(scale);
}
float newRotation = getRotation(event);
setRotation(oldRotation + newRotation);
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
break;
}
return true;
}
private float getDistance(MotionEvent event) {
float dx = event.getX(1) - event.getX(0);
float dy = event.getY(1) - event.getY(0);
return (float) Math.sqrt(dx * dx + dy * dy);
}
private PointF getMidPoint(MotionEvent event) {
float x = (event.getX(1) + event.getX(0)) / 2;
float y = (event.getY(1) + event.getY(0)) / 2;
return new PointF(x, y);
}
private float getRotation(MotionEvent event) {
double delta_x = (event.getX(1) - event.getX(0));
double delta_y = (event.getY(1) - event.getY(0));
double radians = Math.atan2(delta_y, delta_x);
return (float) Math.toDegrees(radians);
}
}
```
在这个示例中,我们重写了onTouchEvent方法,并且根据手势的不同来判断当前的模式(旋转或缩放)。在旋转模式下,我们获取当前的旋转角度,并将其设置为视图的旋转角度。在缩放模式下,我们计算出两个手指之间的距离,并根据距离的变化来设置视图的缩放比例和旋转角度。这样,我们就可以实现多点触控的放大缩小和旋转功能了。
需要注意的是,在这个示例中,我们没有重写onDraw方法,因为我们并不需要在绘制过程中进行任何特殊的操作。如果你需要在绘制过程中进行一些自定义的操作,你可以在自定义视图中重写onDraw方法,并在其中实现你的逻辑。
阅读全文