版权声明: https://blog.csdn.net/GISuuser/article/details/83095206
主要是实现了手指在屏幕上滑动实现平移,两个手指进行缩放。主要是这部分矩阵还挺麻烦的。
效果图如下所示:
核心部分代码如下
触控事件处理:
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
//ACTION_DOWN不return true,就无触发后面的各个事件
if (motionEvent != null) {
final float normalizedX =toOpenGLCoord(view,motionEvent.getX(),true);
final float normalizedY =toOpenGLCoord(view,motionEvent.getY(),false);
switch (motionEvent.getActionMasked()){
case MotionEvent.ACTION_DOWN:
X=normalizedX;
Y=normalizedY;
break;
case MotionEvent.ACTION_POINTER_DOWN:
isZooming=true;
float x1=toOpenGLCoord(view,motionEvent.getX(1),true);
float y1=toOpenGLCoord(view,motionEvent.getY(1),false);
dis_start=computeDis(normalizedX,x1,normalizedY,y1);
break;
case MotionEvent.ACTION_MOVE:
if(isZooming){
float x2=toOpenGLCoord(view,motionEvent.getX(1),true);
float y2=toOpenGLCoord(view,motionEvent.getY(1),false);
double dis=computeDis(normalizedX,x2,normalizedY,y2);
double scale=dis/dis_start;
zoom((float) scale);
dis_start=dis;
}else {
move(normalizedX - X, normalizedY - Y);
X = normalizedX;
Y = normalizedY;
}
break;
case MotionEvent.ACTION_POINTER_UP:
isZooming=false;
X = normalizedX;
Y = normalizedY;
break;
case MotionEvent.ACTION_UP:
break;
default:break;
}
return true;
}
return false;
}
/**
* 屏幕坐标系点转OpenGL坐标系
* @return
*/
private static float toOpenGLCoord(View view,float value,boolean isWidth){
if(isWidth){
return (value / (float) view.getWidth()) * 2 - 1;
}else {
return -((value / (float) view.getHeight()) * 2 - 1);
}
}
/**
* 计算两个点之间的距离
* @param x1
* @param x2
* @param y1
* @param y2
* @return
*/
private static double computeDis(float x1,float x2,float y1,float y2){
return sqrt(pow((x2-x1),2)+pow((y2-y1),2));
}
render部分矩阵处理:
private final float[] translateMatrix = new float[16];//平移矩阵
private final float[] zoomMatrix = new float[16];//缩放矩阵
@Override
public void onSurfaceCreated(GL10 gl10, EGLConfig eglConfig) {
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
//初始化平移矩阵和缩放矩阵为单位矩阵
setIdentityM(translateMatrix,0);//建立单位矩阵
setIdentityM(zoomMatrix,0);//建立单位矩阵
}
@Override
public void onDrawFrame(GL10 gl10) {
glClear(GL_COLOR_BUFFER_BIT);
//平移支持
//两个矩阵相乘
float[] temp = new float[16];
multiplyMM(temp, 0, projectionMatrix, 0, translateMatrix, 0);
float[] temp2 = new float[16];
multiplyMM(temp2, 0, zoomMatrix, 0, temp, 0);
Log.e(TAG,"重新绘制");
for(int i=0;i<brushes.size();i++){
Brush brush=brushes.get(i);
brush.draw(temp2);
}
}
/**
* 改变绘图坐标系的偏移值
* @param dx
* @param dy
*/
public void move(float dx, float dy){
//根据当前缩放的比例调节平移参数
translateM(translateMatrix,0,dx/zoomMatrix[0],dy/zoomMatrix[0],0);//添加平移参数
}
/**
* 缩放视图
* @param scale 缩放比例
*/
public void zoom(float scale){
scaleM(zoomMatrix,0,scale,scale,0);//添加缩放参数
}