问题:图像旋转然后移动,发现移动距离出现错误,位置跳跃问题。
前端关键代码:
<Viewbox x:Name="imageview" Width="480" Height="480" Stretch="Fill" >
<Image x:Name="MyImage" Width="480" Height="480" Source="/Viewer;component/Images/p29.png" HorizontalAlignment="Center" VerticalAlignment="Center" RenderTransformOrigin="0.5,0.5" SnapsToDevicePixels="True" Stretch="Fill"
PreviewMouseLeftButtonDown="PreviewMouseLeftButtonDown" PreviewMouseMove="PreviewMouseMove" PreviewMouseLeftButtonUp="PreviewMouseLeftButtonUp">
<Image.RenderTransform>
<TransformGroup>
<SkewTransform/>
<RotateTransform x:Name="RotateAngle" Angle="{Binding RotateValue ,ElementName=RotateBtn}"/>
<TranslateTransform/>
</TransformGroup>
</Image.RenderTransform>
</Image>
</Viewbox>
后台逻辑主要代码:
Point m_offset = new Point(0, 0);
bool m_isDrag = false;
private void PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
FrameworkElement el = (FrameworkElement)sender;
m_offset = e.GetPosition(el);
m_isDrag = true;
}
private void PreviewMouseMove(object sender, MouseEventArgs e)
{
if (m_isDrag && e.LeftButton == MouseButtonState.Pressed)
{
this.imageview.Cursor = Cursors.SizeAll;
Point p = e.GetPosition((FrameworkElement)sender);
double x = imageview.Margin.Left + (p.X - m_offset.X);
double y = imageview.Margin.Top + (p.Y - m_offset.Y);
if (Math.Abs(x) > 10 || Math.Abs(y) > 10)
{
imageview.Margin = new Thickness(x, y, 0, 0);
}
}
}
private void PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (m_isDrag)
{
m_isDrag = false;
}
this.imageview.Cursor = Cursors.Arrow;
}
分析原因:这是由于坐标系不统一造成的。图像旋转中心点会随之改变,平移坐标x,y移动方向会发生旋转改变,会影响平移的偏移值。为了方便理解画了张图,图像旋转图如下:
方法一:对图像旋转,不对图像移动,移动操作放在其上一层控件上。
<Viewbox x:Name="imageview" Width="480" Height="480" Stretch="Fill" StretchDirection="Both">
<Border HorizontalAlignment="Stretch" VerticalAlignment="Stretch" PreviewMouseLeftButtonDown="PreviewMouseLeftButtonDown" PreviewMouseMove="PreviewMouseMove" PreviewMouseLeftButtonUp="PreviewMouseLeftButtonUp">
<Image x:Name="MyImage" Width="480" Height="480" Source="/Viewer;component/Images/p29.png" HorizontalAlignment="Center" VerticalAlignment="Center" RenderTransformOrigin="0.5,0.5" SnapsToDevicePixels="True" Stretch="Fill" >
<Image.RenderTransform>
<TransformGroup>
<SkewTransform/>
<RotateTransform x:Name="RotateAngle" Angle="{Binding RotateValue ,ElementName=RotateBtn}"/>
<TranslateTransform/>
</TransformGroup>
</Image.RenderTransform>
</Image>
</Border>
</Viewbox>
方法二:对图像旋转、平移,对其坐标旋转。
private void PreviewMouseMove(object sender, MouseEventArgs e)
{
if (this.ZommBtn.ZoomValue <= 100.0)
return;
if (m_isDrag && e.LeftButton == MouseButtonState.Pressed)
{
this.imageview.Cursor = Cursors.SizeAll;
Point p = e.GetPosition((FrameworkElement)sender);
Point ptChange = RotateAngle.Transform(new Point((p.X - m_offset.X), (p.Y - m_offset.Y)));
double x = imageview.Margin.Left + ptChange.X;
double y = imageview.Margin.Top + ptChange.Y;
if (Math.Abs(x) > 10 || Math.Abs(y) > 10)
{
imageview.Margin = new Thickness(x, y, 0, 0);
}
}
}