【发布时间】:2016-01-26 17:00:51
【问题描述】:
我为 ImageView 实现了 ACTION_MOVE,它比它的父级 (FrameLayout) 大。现在我正在尝试添加一些代码,以在至少一个图像边缘位于其父级内部时停止移动(拖动和捏缩放)(因此它不会显示父级的背景)。
我使用了this question中的代码。
case MotionEvent.ACTION_MOVE:
if (mode == DRAG) { //movement of first finger
matrix.set(savedMatrix);
float newX = event.getX() - start.x;
float newY = event.getY() - start.y;
if (view.getLeft() >= -392){
matrix.postTranslate(newX, newY);
}
}
else if (mode == ZOOM) { //pinch zooming
float[] f = new float[9];
float newDist = spacing(event);
if (newDist > 5f) {
matrix.set(savedMatrix);
scale = newDist / oldDist;
matrix.postScale(scale, scale, mid.x, mid.y);
}
matrix.getValues(f);
float scaleX = f[Matrix.MSCALE_X];
float scaleY = f[Matrix.MSCALE_Y];
if(scaleX <= MIN_ZOOM) {
matrix.postScale((MIN_ZOOM)/scaleX,
(MIN_ZOOM)/scaleY, mid.x, mid.y);
}
else if(scaleX >= MAX_ZOOM) {
matrix.postScale((MAX_ZOOM)/scaleX,
(MAX_ZOOM)/scaleY, mid.x, mid.y);
}
}
break;
我尝试了很多东西,我知道已经有人问过类似的问题,但到目前为止没有一个问题适合我的需要。
我最好的猜测是在下面添加代码,但看起来 mImageView.getLeft()、mImageView.getRight() 等返回父级边缘而不是图像。
在 onCreate() 中:
DisplayMetrics displayMetrics =
getApplicationContext().getResources().getDisplayMetrics();
float screenWidth = displayMetrics.widthPixels;
float screenHeight = displayMetrics.heightPixels;
在case MotionEvent.ACTION_MOVE
if (mImageView.getLeft() > 0 ||
mImageView.getRight() < screenWidth) {
matrix.postTranslate(0, newY);
break;
}
else if (mImageView.getTop() > 0 ||
mImageView.getBottom() < screenHeight) {
matrix.postTranslate(newX, 0);
break;
}
else {
matrix.postTranslate(newX, newY);
}
这是我的布局:
<RelativeLayout
android:id="@+id/imageViewContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/mag_background">
<TextView/>
<ImageView/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/imageViewHeadingLabel">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/image"
android:scaleType="matrix"
android:layout_gravity="center_vertical|center_horizontal"
android:contentDescription="image to zoom"/>
</FrameLayout>
</RelativeLayout>
提前感谢您的帮助!
【问题讨论】:
标签: java android matrix android-imageview scale