C#将一个点从一个屏幕坐标转换为另一屏幕坐标
本文关键字:屏幕坐标 一个 转换 | 更新日期: 2023-09-27 18:22:17
我在320*240
坐标系中有一个点,我想变换到不同的坐标系,比如1024*768
或1920*1600
。
是否有预定义的.net
类来实现这一点
我正试图这样解决它-
screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;
double newWidth = x / 320 * screenWidth;
double newHeight = y / 240 * screenHeight;
bola.SetValue(Canvas.LeftProperty, newWidth);
bola.SetValue(Canvas.TopProperty, newHeight);
我从320*240
坐标系中得到一个点,并试图将其移动到另一个坐标系。
有更好的方法来实现这一点吗
其次,我一直在强调这一点,有没有更好的方法来平滑它,因为它在运动中非常紧张?
感谢
如果两个参考系中的原点相同,情况如何(0,0);你唯一能做的就是通过一个简单的三条规则将值从一个系统缩放到另一个系统:
curX -> in 340
newX -> in newWidth(1024)
newX = newWidth(1024) * curX/340 OR newX = curX * ratio_newWidthToOldWidth
高度相同(newY = curY * ratio_newHeightToOldHeight
)。
这已经是一种非常简单的方法了,为什么要寻找更简单的替代方案呢?
在任何情况下,您都应该记住,宽度/高度比会从一种分辨率变化到另一种分辨率(即,您提供的示例中的1.33和1.2),因此,如果您盲目地应用这种转换,对象的外观可能会发生变化(会适应给定的屏幕,但可能看起来比您想要的更糟糕)。因此,您可能希望保持原始的宽高比,并执行以下操作:
newX = ...
newY = ...
if(newX / newY != origXYRatio)
{
newX = newY * origXYRatio // or vice versa
}
因此,在这种情况下,您只需要计算一个变量,X或Y。
您正在将坐标从某个虚拟系统(即320x240)转换为实际坐标系统(即PrimaryScreenWidth
x PrimaryScreenHeight
)。我认为没有比你现在做的更好的方法了。
为了提高代码的可读性,您可以引入一个函数来更好地传达您的意图:
// Or whatever the type of "ctl" is ...
private void SetPositionInVirtualCoords(Control ctl, double x, double y)
{
screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;
ctl.SetValue(Canvas.LeftProperty, x * (screenWidth/320.0));
ctl.SetValue(Canvas.TopProperty, y * (screenHeight/240.0));
}
以便您的主代码可以读取为:
SetPositionInVirtualCoords(bola, x, y);
并且也可以被其他控件重新使用。