(Xamarin与Visual Studio 2015)我想用Imageview实现一个简单的Activity,它可以通过触摸移动/拖动:这是我实现的,但是图像闪烁并且移动得更慢。你能举个例子来说明如何实现这个吗? 谢谢你的帮助!
private void TouchMeImageViewOnTouch(object sender, View.TouchEventArgs touchEventArgs)
{
View bild = (View)sender;
RelativeLayout.LayoutParams layouti = (RelativeLayout.LayoutParams)bild.LayoutParameters;
switch (touchEventArgs.Event.Action & MotionEventActions.Mask)
{
case MotionEventActions.Down:
xDelta = touchEventArgs.Event.GetX()-layouti.LeftMargin;
yDelta = touchEventArgs.Event.GetX() - layouti.LeftMargin;
break;
case MotionEventActions.Move:
int wert = (int)touchEventArgs.Event.GetX();
yvalue = touchEventArgs.Event.GetY()-yDelta;
xvalue = touchEventArgs.Event.GetX()-xDelta;
float xdpi = (int) Resources.DisplayMetrics.Density;
layouti.LeftMargin = (int)xvalue;
layouti.TopMargin = (int)yvalue;
container.Invalidate();
break;
case MotionEventActions.Up:
break;
default:
break;
}
xPositionText.Text = xvalue.ToString();
yPositionText.Text = yvalue.ToString();
}
答案 0 :(得分:1)
我试图实现可拖动的imageview进行测试。 Android模拟器中的拖动速度很慢。但是通过在真实设备中进行测试,它可以正常工作并快速移动。
尝试以下代码示例:
public class MainActivity : Activity, IOnTouchListener
{
Button dragAbleBt;
ImageView imgV1;
int screenWidth = 0;
int screenHeight = 0;
int lastX = 0, lastY = 0;
public bool OnTouch(View v, MotionEvent e)
{
MotionEventActions ea = e.Action;
switch (ea) {
case MotionEventActions.Down:
lastX = (int)e.RawX;
lastY = (int)e.RawY;
break;
case MotionEventActions.Move:
int dx = (int)e.RawX - lastX;
int dy = (int)e.RawY - lastY;
int left = v.Left + dx;
int right = v.Right + dx;
int top = v.Top + dy;
int bottom = v.Bottom + dy;
if (left < 0)
{
left = 0;
right = left + v.Width;
}
if (right > screenWidth)
{
right = screenWidth;
left = right - v.Width;
}
if (top < 0)
{
top = 0;
bottom = top + v.Height;
}
if (bottom > screenHeight)
{
bottom = screenHeight;
top = bottom - v.Height;
}
v.Layout(left, top, right, bottom);
lastX = (int) e.RawX;
lastY = (int) e.RawY;
v.PostInvalidate();
break;
case MotionEventActions.Up:
break;
}
if (v.Id == Resource.Id.imageView1)
{
return true;
}
return false;
}
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView (Resource.Layout.Main);
//DisplayMetrics dm = Resources.DisplayMetrics;
//screenWidth = dm.WidthPixels;
//screenHeight = dm.HeightPixels;
dragAbleBt = FindViewById<Button>(Resource.Id.button1);
imgV1 = FindViewById<ImageView>(Resource.Id.imageView1);
dragAbleBt.SetOnTouchListener(this);
imgV1.SetOnTouchListener(this);
}
public override void OnWindowFocusChanged(bool hasFocus)
{
base.OnWindowFocusChanged(hasFocus);
if (hasFocus)
{
Rect outRect = new Rect();
this.Window.FindViewById(Window.IdAndroidContent).GetDrawingRect(outRect);
screenWidth = outRect.Width();
screenHeight = outRect.Height();
}
}
}
请参阅源代码github