对于WPF而言,我是业余爱好者,我正在与我的男孩一起为他的Lego Mindstorms机器人建立用户界面。
他让我用方向盘代替方向按钮,虽然我能做到这一点,包括旋转变换,但我不知道如何让鼠标向下移动/拖动事件,相对于拖动方向。
到目前为止我的XAML是这样的:
<Image x:Name="steering" HorizontalAlignment="Left" Height="146" Margin="253,67,0,0"
VerticalAlignment="Top" Width="146" Source="images/steering-wheel.png" RenderTransformOrigin="0.5,0.5">
<Image.RenderTransform>
<RotateTransform CenterX="0.5" CenterY="0.5" />
</Image.RenderTransform>
<Image.Triggers>
<EventTrigger RoutedEvent="Loaded">
<BeginStoryboard>
<Storyboard RepeatBehavior="Forever">
<DoubleAnimation Storyboard.TargetProperty="(Image.RenderTransform).(RotateTransform.Angle)"
From="0" To="360" Duration="0:0:2" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Image.Triggers>
</Image>
我之后检测到用户是什么时候&#34;拖动&#34;方向盘向左或向右,并相应地改变图像的旋转角度。我应该从哪里开始?
答案 0 :(得分:1)
我做过类似的事情
你需要2个参考点来计算方向盘中心的旋转和鼠标的位置,如下所示
private void Steering_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
var control = sender as Ellipse;
var point = e.GetPosition(control);
var centre = new Point(control.Width / 2, control.Height / 2);
var vector = point - centre
Steering.Angle = (Math.Atan2(vector.X,vector.Y) * 180 / Math.PI);
//note default behaviour of Atan2 is Angle 0 = East and Anti Clockwise is a positive angle,
//by swapping X and Y north is now 0 angle and clockwise is positive
}
}
然后你只需要绑定旋转
<Ellipse
MouseMove="Steering_MouseMove" >
<Ellipse.RenderTransform>
<RotateTransform Angle="{Binding Steering.Angle}" CenterX="0.5" CenterY="0.5"/>
</Ellipse.RenderTransform>
</Ellipse>