如何在android中设置图像移动的边界
我创建了一个图像视图,并使用OnTouchListener将其移动。如何将移动限制在屏幕的边界?您可以计算屏幕大小,并修复屏幕内的图像移动,如下图所示如何在android中设置图像移动的边界,android,android-view,Android,Android View,我创建了一个图像视图,并使用OnTouchListener将其移动。如何将移动限制在屏幕的边界?您可以计算屏幕大小,并修复屏幕内的图像移动,如下图所示 Display display = getWindowManager().getDefaultDisplay(); width = display.getWidth(); height = display.getHeight(); 你不想要一个听众,你想要一个听众。查找不同的DrageEvent操
Display display = getWindowManager().getDefaultDisplay();
width = display.getWidth();
height = display.getHeight();
你不想要一个听众,你想要一个听众。查找不同的DrageEvent操作类型以获取有关视图所在位置的信息。从那里,只要您知道视图的尺寸,就可以禁止它移出屏幕。我根据在这里找到的代码做了类似的操作: 它基于谷歌的启动程序代码。为了保持屏幕上的视图,我修改了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();
这里呢
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();
如果要在页面中显示图像,请使用以下代码:
<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>
你应该接受其中一个答案。