android imageView:设置拖动和捏缩放参数

时间:2010-11-19 17:01:16

标签: android drag-and-drop imageview zoom pinch

我目前正在为Android(我的第一个应用程序)开发一个应用程序,该应用程序可让用户查看地铁地图并能够进行缩放和拖动。

我目前正在修改Hello Android第3版中的代码,并进行了缩放缩放和拖动工作。我正在使用Matrix作为我的布局比例。

但是我现在有3个问题:

  1. 我尝试了很多东西来限制拖动参数,但我似乎无法阻止它被拖出父视图(并且实际上可以从视图中消失)。我已经尝试在XML文件中设置布局参数,但它不起作用。

  2. 我可以捏缩放,但我又遇到了麻烦,限制了变焦量。我正在尝试设置max_zoom和min_zoom以限制缩放值(我将在之后发布我的代码)

  3. 我也无法在图像上映射坐标,以便人们可以点击某些部分(这一点的全部内容是让用户点击地图上的一个工作站并查看有关它的信息)

  4. 我有一种感觉我遇到了麻烦,因为我正在使用矩阵比例。

    这是我目前的代码:

    Touch.java

    package org.example.touch;
    import android.app.Activity;
    import android.graphics.Bitmap;
    import android.graphics.Matrix;
    import android.graphics.PointF;
    import android.os.Bundle;
    import android.util.FloatMath;
    import android.util.Log;
    import android.view.MotionEvent;
    import android.view.View;
    import android.view.View.OnTouchListener;
    import android.widget.GridView;
    import android.widget.ImageView;
    
    public class Touch extends Activity implements OnTouchListener {
    private static final String TAG = "Touch";
    
    private static final float MIN_ZOOM = 1.0f;
    private static final float MAX_ZOOM = 5.0f;
    
    // These matrices will be used to move and zoom image
    Matrix matrix = new Matrix();
    Matrix savedMatrix = new Matrix();
    
    // We can be in one of these 3 states
    static final int NONE = 0;
    static final int DRAG = 1;
    static final int ZOOM = 2;
    int mode = NONE;
    
    // Remember some things for zooming
    PointF start = new PointF();
    PointF mid = new PointF();
    float oldDist = 1f;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       ImageView view = (ImageView) findViewById(R.id.imageView);
       //view.setLayoutParams(new GridView.LayoutParams(85, 85));
       view.setScaleType(ImageView.ScaleType.FIT_CENTER);
       view.setOnTouchListener(this);   
    }
    
    public boolean onTouch(View v, MotionEvent event) {
       ImageView view = (ImageView) v;
       view.setScaleType(ImageView.ScaleType.MATRIX);
       float scale;
    
       // Dump touch event to log
       dumpEvent(event);
    
       // Handle touch events here...
       switch (event.getAction() & MotionEvent.ACTION_MASK) {
    
       case MotionEvent.ACTION_DOWN: //first finger down only
          savedMatrix.set(matrix);
          start.set(event.getX(), event.getY());
          Log.d(TAG, "mode=DRAG" );
          mode = DRAG;
          break;
       case MotionEvent.ACTION_UP: //first finger lifted
       case MotionEvent.ACTION_POINTER_UP: //second finger lifted
          mode = NONE;
          Log.d(TAG, "mode=NONE" );
          break;
       case MotionEvent.ACTION_POINTER_DOWN: //second finger down
          oldDist = spacing(event);
          Log.d(TAG, "oldDist=" + oldDist);
          if (oldDist > 5f) {
             savedMatrix.set(matrix);
             midPoint(mid, event);
             mode = ZOOM;
             Log.d(TAG, "mode=ZOOM" );
          }
          break;
    
       case MotionEvent.ACTION_MOVE: 
          if (mode == DRAG) { //movement of first finger
             matrix.set(savedMatrix);
             if (view.getLeft() >= -392){
                matrix.postTranslate(event.getX() - start.x, event.getY() - start.y);
             }
          }
          else if (mode == ZOOM) { //pinch zooming
             float newDist = spacing(event);
             Log.d(TAG, "newDist=" + newDist);
             if (newDist > 5f) {
                matrix.set(savedMatrix);
                scale = newDist / oldDist; **//thinking i need to play around with this value to limit it**
                matrix.postScale(scale, scale, mid.x, mid.y);
             }
          }
          break;
       }
    
       // Perform the transformation
       view.setImageMatrix(matrix);
    
       return true; // indicate event was handled
    }
    
    private float spacing(MotionEvent event) {
       float x = event.getX(0) - event.getX(1);
       float y = event.getY(0) - event.getY(1);
       return FloatMath.sqrt(x * x + y * y);
    }
    
    private void midPoint(PointF point, MotionEvent event) {
       float x = event.getX(0) + event.getX(1);
       float y = event.getY(0) + event.getY(1);
       point.set(x / 2, y / 2);
    }
    
    /** Show an event in the LogCat view, for debugging */
    private void dumpEvent(MotionEvent event) {
       String names[] = { "DOWN" , "UP" , "MOVE" , "CANCEL" , "OUTSIDE" ,
          "POINTER_DOWN" , "POINTER_UP" , "7?" , "8?" , "9?" };
       StringBuilder sb = new StringBuilder();
       int action = event.getAction();
       int actionCode = action & MotionEvent.ACTION_MASK;
       sb.append("event ACTION_" ).append(names[actionCode]);
       if (actionCode == MotionEvent.ACTION_POINTER_DOWN
             || actionCode == MotionEvent.ACTION_POINTER_UP) {
          sb.append("(pid " ).append(
          action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
          sb.append(")" );
       }
       sb.append("[" );
       for (int i = 0; i < event.getPointerCount(); i++) {
          sb.append("#" ).append(i);
          sb.append("(pid " ).append(event.getPointerId(i));
          sb.append(")=" ).append((int) event.getX(i));
          sb.append("," ).append((int) event.getY(i));
          if (i + 1 < event.getPointerCount())
             sb.append(";" );
       }
       sb.append("]" );
       Log.d(TAG, sb.toString());
    }
    }
    

    main.xml(相当简单,没有什么真正复杂的):

    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent" >
    <ImageView android:id="@+id/imageView"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"
         android:src="@drawable/map"
         android:scaleType="matrix" >
    </ImageView>
    </FrameLayout>
    

    AndroidManifest.xml(仅添加了主题,因此没有标题栏并且是全屏)

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="org.example.touch"
      android:versionCode="7"
      android:versionName="1.0" >
    <application android:icon="@drawable/icon" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >
      <activity android:name=".Touch"
            android:label="@string/app_name" >
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
    </application>
    <uses-sdk android:minSdkVersion="3" android:targetSdkVersion="7" />
    </manifest>
    

7 个答案:

答案 0 :(得分:18)

我刚刚创建了这个:

https://github.com/jasonpolites/gesture-imageview

可能对某人有用......

答案 1 :(得分:12)

另一个可能适用于某些选项的选项是使用内置缩放控件的WebView

WebView webView = new WebView(this);
webView.setBackgroundColor(0xff000000);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSupportZoom(true);
//webView.getSettings().setDisplayZoomControls(false);  // API 11
webView.loadDataWithBaseURL(null, getHtml(), "text/html", "UTF-8", null);
mainView.addView(webView, -1, -2);

答案 2 :(得分:7)

我知道这已经过时了,但我正在考虑这样做,并且有一个非常好的解决方案。在切换语句之后和设置矩阵之前,您可以像这样限制缩放:

private void limitZoom(Matrix m) {

    float[] values = new float[9];
    m.getValues(values);
    float scaleX = values[Matrix.MSCALE_X];
    float scaleY = values[Matrix.MSCALE_Y];
    if(scaleX > MAX_ZOOM) {
        scaleX = MAX_ZOOM;
    } else if(scaleX < MIN_ZOOM) {
        scaleX = MIN_ZOOM;
    }

    if(scaleY > MAX_ZOOM) {
        scaleY = MAX_ZOOM;
    } else if(scaleY < MIN_ZOOM) {
        scaleY = MIN_ZOOM;
    }

    values[Matrix.MSCALE_X] = scaleX;
    values[Matrix.MSCALE_Y] = scaleY; 
    m.setValues(values);
}

我还在研究如何限制翻译,但这应该适用于缩放限制。

编辑:这是限制翻译的解决方案。就像一张纸条,我这样做是为了全屏图像视图,这就是我在限制因素中使用显示宽度和高度的原因,但你可以轻松地使用视图的宽度和高度。

private void limitDrag(Matrix m) {
    float[] values = new float[9];
    m.getValues(values);
    float transX = values[Matrix.MTRANS_X];
    float transY = values[Matrix.MTRANS_Y];
    float scaleX = values[Matrix.MSCALE_X];
    float scaleY = values[Matrix.MSCALE_Y];

    ImageView iv = (ImageView)findViewById(R.id.photo_view);
    Rect bounds = iv.getDrawable().getBounds();
    int viewWidth = getResources().getDisplayMetrics().widthPixels;
    int viewHeight = getResources().getDisplayMetrics().heightPixels;

    int width = bounds.right - bounds.left;
    int height = bounds.bottom - bounds.top;

    float minX = (-width + 20) * scaleX; 
    float minY = (-height + 20) * scaleY;

    if(transX > (viewWidth - 20)) {
        transX = viewWidth - 20;
    } else if(transX < minX) {
        transX = minX;
    }

    if(transY > (viewHeight - 80)) {
        transY = viewHeight - 80;
    } else if(transY < minY) {
        transY = minY;
    }

    values[Matrix.MTRANS_X] = transX;
    values[Matrix.MTRANS_Y] = transY; 
    m.setValues(values);
}

再一次,这将在你的switch语句之后,就在为视图中的图像设置矩阵之前。我也将缩放限制分解成了一个函数,它反映在上面。

答案 3 :(得分:6)

下载源代码。 所以你也可以得到这个a)轻拍,b)拖动,和c)捏缩放。 http://pragprog.com/titles/eband3/source_code

答案 4 :(得分:6)

以下是捏缩放和平移的完整代码(Touch.java带有一些可以实际使用的修改)

public class Touch implements OnTouchListener {  

 // These matrices will be used to move and zoom image  
public static Matrix matrix = new Matrix();  
public static Matrix savedMatrix = new Matrix();  

 // We can be in one of these 3 states  
 static final int NONE = 0;  
 static final int DRAG = 1;  
 static final int ZOOM = 2;
private static final float MAX_ZOOM = (float) 3;
private static final float MIN_ZOOM = 1;  
 int mode = NONE;  

 // Remember some things for zooming  
 PointF start = new PointF();  
 PointF mid = new PointF();  
 float oldDist = 1f;  

 int width,height;

 @Override  
 public boolean onTouch(View v, MotionEvent event) {


  ImageView view = (ImageView) v;
  Rect bounds = view.getDrawable().getBounds();

  width = bounds.right - bounds.left;
  height = bounds.bottom - bounds.top;
  // Dump touch event to log  
  dumpEvent(event);  

  // Handle touch events here...  
  switch (event.getAction() & MotionEvent.ACTION_MASK) {  
  case MotionEvent.ACTION_DOWN:  
   savedMatrix.set(matrix);  
   start.set(event.getX(), event.getY());  
   mode = DRAG;  
   break;  
  case MotionEvent.ACTION_POINTER_DOWN:  
   oldDist = spacing(event);  
   if (oldDist > 10f) {  
    savedMatrix.set(matrix);  
    midPoint(mid, event);  
    mode = ZOOM;  
   }  
   break;  
  case MotionEvent.ACTION_UP:  
  case MotionEvent.ACTION_POINTER_UP:  
   mode = NONE;  
   break;  
  case MotionEvent.ACTION_MOVE:  
   if (mode == DRAG) {  
    // ...      
    matrix.set(savedMatrix);  
    matrix.postTranslate(event.getX() - start.x, event.getY() - start.y);      
   } else if (mode == ZOOM) {  
    float newDist = spacing(event);  
    if (newDist > 10f) {  
     matrix.set(savedMatrix);  
     float scale = newDist / oldDist;  
     matrix.postScale(scale, scale, mid.x, mid.y);  
    }  
   }  
   break;  
  }  
//----------------------------------------------------
  limitZoom(matrix);
  limitDrag( matrix);
//----------------------------------------------------  
  view.setImageMatrix(matrix);  
  return true; // indicate event was handled  
 }  

 /** Show an event in the LogCat view, for debugging */  
 private void dumpEvent(MotionEvent event) {  
  String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE",  
    "POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };  
  StringBuilder sb = new StringBuilder();  
  int action = event.getAction();  
  int actionCode = action & MotionEvent.ACTION_MASK;  
  sb.append("event ACTION_").append(names[actionCode]);  
  if (actionCode == MotionEvent.ACTION_POINTER_DOWN  
    || actionCode == MotionEvent.ACTION_POINTER_UP) {  
   sb.append("(pid ").append(  
     action >> MotionEvent.ACTION_POINTER_ID_SHIFT);  
   sb.append(")");  
  }  
  sb.append("[");  
  for (int i = 0; i < event.getPointerCount(); i++) {  
   sb.append("#").append(i);  
   sb.append("(pid ").append(event.getPointerId(i));  
   sb.append(")=").append((int) event.getX(i));  
   sb.append(",").append((int) event.getY(i));  
   if (i + 1 < event.getPointerCount())  
    sb.append(";");  
  }  
  sb.append("]");  
 }  

 /** Determine the space between the first two fingers */  
 private float spacing(MotionEvent event) {  
  float x = event.getX(0) - event.getX(1);  
  float y = event.getY(0) - event.getY(1);  
  return FloatMath.sqrt(x * x + y * y);  
 }  

 /** Calculate the mid point of the first two fingers */  
 private void midPoint(PointF point, MotionEvent event) {  
  float x = event.getX(0) + event.getX(1);  
  float y = event.getY(0) + event.getY(1);  
  point.set(x / 2, y / 2);  
 }  

 private void limitZoom(Matrix m) {

        float[] values = new float[9];
        m.getValues(values);
        float scaleX = values[Matrix.MSCALE_X];
        float scaleY = values[Matrix.MSCALE_Y];
        if(scaleX > MAX_ZOOM) {
            scaleX = MAX_ZOOM;
        } else if(scaleX < MIN_ZOOM) {
            scaleX = MIN_ZOOM;
        }

        if(scaleY > MAX_ZOOM) {
            scaleY = MAX_ZOOM;
        } else if(scaleY < MIN_ZOOM) {
            scaleY = MIN_ZOOM;
        }

        values[Matrix.MSCALE_X] = scaleX;
        values[Matrix.MSCALE_Y] = scaleY; 
        m.setValues(values);
    }


 private void limitDrag(Matrix m) {

        float[] values = new float[9];
        m.getValues(values);
        float transX = values[Matrix.MTRANS_X];
        float transY = values[Matrix.MTRANS_Y];
        float scaleX = values[Matrix.MSCALE_X];
        float scaleY = values[Matrix.MSCALE_Y];
//--- limit moving to left ---
        float minX = (-width + 0) * (scaleX-1); 
        float minY = (-height + 0) * (scaleY-1);
//--- limit moving to right ---     
        float maxX=minX+width*(scaleX-1);
        float maxY=minY+height*(scaleY-1);
        if(transX>maxX){transX = maxX;}
        if(transX<minX){transX = minX;}
        if(transY>maxY){transY = maxY;}
        if(transY<minY){transY = minY;}
        values[Matrix.MTRANS_X] = transX;
        values[Matrix.MTRANS_Y] = transY; 
        m.setValues(values);
    }

}

答案 5 :(得分:5)

使用以下链接中的Phyxdevel评论中的代码 ZDNET Pinch Zoom Example

他有限制平移和缩放级别的代码。

答案 6 :(得分:0)

您可以使用以下代码来限制底部和右侧

float maxX = minX+viewWidth; 
int offsetY = 80;
        float maxY = minY+viewHeight-offsetY;
       if(x>maxX){
           mPosX = maxX;
       }
       if(x<minX){
           mPosX = minX;
       }
       if(y>maxY){
           mPosY = maxY;
       }
       if(y<minY){
           mPosY = minY;
       }