通过鼠标UWP旋转视图上的Ui对象
本文关键字:Ui 对象 视图 旋转 鼠标 UWP | 更新日期: 2023-09-27 18:12:36
我需要使用鼠标旋转Image
。我不知道该怎么做。现在我有了通过按
private void Rotate_Click(object sender, RoutedEventArgs e)
{
var button = sender as Button;
var parent = (FrameworkElement) VisualTreeHelper.GetParent(button);
var ct = (CompositeTransform) parent.RenderTransform;
ct.Rotation += 5;
}
但是我怎样才能把它改成我的要求呢?我需要拖动按钮并旋转
下面是一个粗略的示例,当拖动时,视图上的图像会围绕其中心旋转。
在新项目中添加XAML
<Image x:Name="TheImage"
Source="Assets/StoreLogo.png"
Width="200"
Stretch="Uniform"
RenderTransformOrigin="0.5,0.5"
PointerPressed="OnPointerPressed"
PointerMoved="OnPointerMoved"
PointerReleased="OnPointerReleased">
<Image.RenderTransform>
<RotateTransform x:Name="ImageRotation" />
</Image.RenderTransform>
</Image>
下面是相应的
后面的代码private bool pointerCaptured = false;
private Point lastPosition;
private void OnPointerPressed(object sender, PointerRoutedEventArgs e)
{
pointerCaptured = true;
this.lastPosition = e.GetCurrentPoint(TheImage).Position;
}
private void OnPointerMoved(object sender, PointerRoutedEventArgs e)
{
if (pointerCaptured)
{
Point currentLocation = e.GetCurrentPoint(this.TheImage).Position;
double radians = Math.Atan((currentLocation.Y - lastPosition.Y) /
(currentLocation.X - lastPosition.X));
var angle = radians * 180 / Math.PI;
// Apply a 180 degree shift when X is negative so can rotate all of the way around
if (currentLocation.X - lastPosition.X < 0)
{
angle += 180;
}
lastPosition = currentLocation;
this.ImageRotation.Angle = angle;
}
}
private void OnPointerReleased(object sender, PointerRoutedEventArgs e)
{
pointerCaptured = false;
}
关于https://stackoverflow.com/a/963099/1755