如何在 WP8 中获取元素的绝对位置并使用它将该元素移动到新位置
我正在尝试使用以下代码在屏幕上点击移动图像并出现意外行为。
private void SetGame()
{
ScreenWidth = Application.Current.Host.Content.ActualWidth;
ScreenHeight = Application.Current.Host.Content.ActualHeight;
var transform = littleMan.TransformToVisual(Application.Current.RootVisual);
System.Windows.Point absolutePosition = transform.Transform(new System.Windows.Point(0, 0));
manLocY = absolutePosition.Y; //vert
manLocX = absolutePosition.X; //hori
leftControlArea = (ScreenWidth / 2);
rightControlArea = (ScreenWidth / 2); // answer to the screen width;
topControlArea = (ScreenHeight / 3);
bottomControlArea = (ScreenHeight / 3) * 2; // answer to the screen height
littleManWidth = littleMan.ActualWidth;
littleManHeight = littleMan.ActualHeight;
}
private void MoveLittleMan(Vector2 tappedWhere)
{
double tapX, tapY;
tapX = tappedWhere.X; // represent where user tapped on screen width wise
tapY = tappedWhere.Y; // represent where user tapped on screen height wise
if(tapY <= topControlArea)
{
// move top
Debug.WriteLine("Move TOP - X: " + tapX + " - Y: " + tapY);
if (manLocY > littleManHeight)
{
manLocY = manLocY - skippingSteps;
Canvas.SetTop(littleMan, manLocY);
}
}
else if(tapY >= bottomControlArea)
{
//move bottom
Debug.WriteLine("Move BOTTOM - X: " + tapX + " - Y: " + tapY);
if (manLocY < (ScreenHeight - littleManHeight))
{
manLocY = manLocY + skippingSteps;
Canvas.SetTop(littleMan, manLocY);
}
}
else if (tapX <= leftControlArea && tapY > topControlArea && tapY < bottomControlArea)
{
//move left
Debug.WriteLine("Move LEFT - X: " + tapX + " - Y: " + tapY);
if (manLocX > littleManWidth)
{
manLocX = manLocX - skippingSteps;
Canvas.SetLeft(littleMan, manLocX);
}
}
else if (tapX > rightControlArea && tapY > topControlArea && tapY < bottomControlArea)
{
//move right
Debug.WriteLine("Move RIGHT - X: " + tapX + " - Y: " + tapY);
if (manLocX < (ScreenWidth - littleManWidth))
{
manLocX = manLocX + skippingSteps;
Canvas.SetLeft(littleMan, manLocX);
}
}
}
预期的行为是,在轻按时,系统将确定屏幕的哪一侧已被轻按,并将小人移动到那个方向。
skippingSteps = 40;
当应用程序启动setGame()
功能运行。我遇到的问题是,当应用程序启动并点击屏幕右侧时,littleMan 跳出屏幕右边界太远。当我按左键时,它开始回来。使用断点,我收集的数据似乎很好,但是当Canvas.SetLeft
orCanvas.SetTop
被称为 littleMan 时,它是 20x20 的 gif 图像跳转到 X 平面中 520 的位置。
有人可以帮助我了解我做错了什么。