android imageView:设置拖动和捏缩放参数
Posted
技术标签:
【中文标题】android imageView:设置拖动和捏缩放参数【英文标题】:android imageView: setting drag and pinch zoom parameters 【发布时间】:2011-05-12 18:20:08 【问题描述】:我目前正在为 android(我的第一个应用程序)开发一个应用程序,它可以让用户查看地铁地图并能够捏缩放和拖动。
我目前正在修改 Hello Android,第 3 版中的代码,并让捏缩放和拖动工作。我使用 Matrix 作为我的布局比例。
但是我现在有 3 个问题:
我尝试了很多方法来限制拖动参数,但我似乎无法阻止它被拖离父视图(实际上可以从视图中消失)。我尝试在 XML 文件中设置布局参数,但它不起作用。
我可以很好地捏缩放,但我又遇到了麻烦,限制缩放量。我正在尝试设置 max_zoom 和 min_zoom 来限制缩放值(我将在之后发布我的代码)
我也很难在我的图像上绘制一个坐标,以便人们可以点击某些部分(这样做的全部目的是让用户点击地图上的一个站点并查看有关它的信息)
我觉得我遇到了麻烦,因为我使用的是矩阵刻度。
这是我当前的代码:
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_
android:layout_ >
<ImageView android:id="@+id/imageView"
android:layout_
android:layout_
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>
【问题讨论】:
【参考方案1】:使用下面链接中 Phyxdevel 评论中的代码 ZDNET Pinch Zoom Example.
他有限制平移和缩放级别的代码。
【讨论】:
【参考方案2】:下载源代码。 所以你也可以得到这个a)点击,b)拖动和c)捏缩放。 http://pragprog.com/titles/eband3/source_code
【讨论】:
【参考方案3】:我刚刚创建了这个:
https://github.com/jasonpolites/gesture-imageview
可能对某人有用...
【讨论】:
fill_parent 的宽度和高度没有意义,因为这会(在大多数情况下)扭曲图像。框架对其中一个轴使用 fill_parent 属性,并根据图像的纵横比计算另一个。它根据设备的方向选择哪个轴。横向意味着宽度是 fill_parent 并计算高度,反之亦然。 @Jason,这将是图像容器的大小,图像本身的大小将在容器的范围内独立。 手势图像视图已更新。现在支持 CENTER、CENTER_CROP 和 CENTER_FILL 的 fill_parent 和 ScaleTypes 这个也支持移动和旋转图片吗?【参考方案4】:我知道这是旧的,但我正在考虑这样做并且有一个效果很好的解决方案。在你的 switch 语句之后和设置矩阵之前,你可以像这样限制缩放:
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 语句之后和您为视图中的图像设置矩阵之前进行。我也将缩放限制分解为一个函数,它反映在上面。
【讨论】:
限制了向上和向左的拖动..但是向右和向下图像仍然可以。有什么解决办法吗? @playmaker420 请检查我下面的答案以限制右下角。 @Ankit..我已经解决了。感谢分享代码 它的工作就像一个魅力。但就我而言,如果我在背景中移动手指,而不是 ImageView,那么 ImageView 也在移动。如何仅在触摸时准确移动图像?请有需要.. 这适用于全屏 ImageView。如果您只想让它适用于图像,那么您需要在调整大小时跟踪图像的大小。这比我在这里的工作要多得多。可能值得就该问题提出一个单独的问题。【参考方案5】:另一个可能适用于某些人的选项是使用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);
【讨论】:
我可以毫无疑问地说,这是我找到的管理缩放位图的最佳方式。我希望你不介意我发布一个链接到另一个可能帮助其他人的 SO 问题,但是这个答案与***.com/questions/10849200/… 结合使用了将动态创建的位图加载到 WebView 中进行缩放的技巧。再次感谢,很好的答案! 对于 Android 11 不要忘记添加以下参数:webview.getSettings().setAllowFileAccess(true);【参考方案6】:您可以使用以下代码来限制底部和右侧
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;
【讨论】:
【参考方案7】:这里是捏缩放和平移的完整代码(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);
【讨论】:
以上是关于android imageView:设置拖动和捏缩放参数的主要内容,如果未能解决你的问题,请参考以下文章