【发布时间】:2013-10-12 21:11:04
【问题描述】:
如何在 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 或 Canvas.SetTop 被称为 littleMan 时,它是一个 20x20 的 gif 图像,会跳转到 X 平面中 520 的位置。
谁能帮我理解我做错了什么。
【问题讨论】:
标签: c# windows silverlight windows-phone-8