-1

我创建了一个图像视图并用OnTouchListener. 如何将移动限制在屏幕边界内?

4

4 回答 4

1

我根据在这里找到的代码做了类似的事情: DragView Example

它基于谷歌的启动器代码。为了将视图保留在屏幕上,我修改了 onTouchEvent 方法以将视图保留在屏幕上。

public boolean onTouchEvent(MotionEvent ev) {
    if (!mDragging) {
        return false;
    }
    final int action = ev.getAction();
    final int screenX = clamp((int)ev.getRawX(), 0, mDisplayMetrics.widthPixels);
    final int screenY = clamp((int)ev.getRawY(), 0, mDisplayMetrics.heightPixels);
    //**ADDED to keep view entirely on screen
    final int[] parentpos = {-1,-1};
    ((View) mDragSource).getLocationOnScreen(parentpos);
    int minScreenX = parentpos[0] + (int)mTouchOffsetX;
    int minScreenY = parentpos[1] + (int)mTouchOffsetY;
    int maxScreenX = minScreenX + ((View) mDragSource).getWidth() - mDragView.getWidth();
    int maxScreenY = minScreenY + ((View) mDragSource).getHeight() - mDragView.getHeight();
    //end ADDED

和这里

    case MotionEvent.ACTION_MOVE:
        // Update the drag view.  Don't use the clamped pos here so the dragging looks
        // like it goes off screen a little, intead of bumping up against the edge.
        // **CHANGED to keep view entirely on screen
        mDragView.move(clamp(screenX,minScreenX,maxScreenX), 
                clamp(screenY,minScreenY,maxScreenY));
        // end CHANGED

和这里

    case MotionEvent.ACTION_UP:
        if (mDragging) {
            // **CHANGED to keep view entirely on screen
            drop(clamp(screenX,minScreenX,maxScreenX), 
                    clamp(screenY,minScreenY,maxScreenY));
            //end CHANGED
        }
        endDrag();
于 2012-04-12T05:44:57.290 回答
1

如果要在页面中显示图像,请使用以下代码:

       <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"
         android:orientation="vertical" >

     <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
         android:layout_height="match_parent"
        android:padding="2px"
        android:src="pathOfImage" />

     </LinearLayout>

或者您可以使用以下代码设置高度和宽度:

    Display display = getWindowManager().getDefaultDisplay();
    width = display.getWidth();
    height = display.getHeight();

    ImageView imageView=(ImageView) findViewById(R.id.image);
    imageView.setLayoutParams(new LayoutParams(width, height));
于 2012-04-12T06:09:17.260 回答
0

你不想要OnTouchListener,你想要OnDragListener。查找不同的DragEvent操作类型以获取有关您的视图所在位置的信息。从那里,只要你知道你的尺寸View,你就可以禁止它移动到屏幕之外。

于 2012-04-12T05:06:16.820 回答
0

你可以计算你的屏幕尺寸,并可以像这样修复屏幕内的图像移动

Display display = getWindowManager().getDefaultDisplay();
            width = display.getWidth();
            height = display.getHeight();
于 2012-04-12T04:59:36.750 回答