2017-09-03 165 views
0

在我的WPF应用程序,我想旋转被放置在一个网格单元的图像:在旋转和自动缩放图片

  • 使用RotateTransform直接:

    <Grid> 
        <Grid.RowDefinitions> 
         <RowDefinition Height="50"/> 
         <RowDefinition/> 
        </Grid.RowDefinitions> 
        <Button Name="btnRotate" Click="btnRotate_Click">Rotate</Button> 
        <Image Grid.Row="1" Name="img" RenderTransformOrigin="0.5,0.5" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" /> 
    </Grid> 
    

    我尝试了两种思路Image集装箱。不幸的是,这种转换取消了容器的属性VerticalAlignment="Stretch" HorizontalAlignment="Stretch",并且图像超出了单元格边界。

  • 在图像的TransformedBitmap实例上使用RotateTransform。这个构造旋转和自动缩放,但GC不收集旧的实例;所以它浪费了很多RAM功能。

这是我的第二个想法背后的代码。如果它不会浪费那么多RAM,那就没问题。

private void btnRotate_Click(object sender, RoutedEventArgs e) 
{ 
    bmp = new TransformedBitmap(bmp, new RotateTransform(90)); 
    bmp.Freeze(); 
    img.Source = bmp; 
} 

那么,在其布局容器中使用自动缩放旋转图像的最佳做法是什么?

+0

你有没有用尽全力RenderTransform和LayoutTransform? – CShark

+0

我只使用RenderTransform。 – User95

+0

在WPF已经计算出所有尺寸和尺寸之后,RenderTransform会被应用。 LayoutTransform更改对象,然后根据更改计算大小。应该值得一试。 – CShark

回答

1

您可以尝试使用LayoutTransform而不是RenderTransform。在WPF已经计算出各个对象的所有大小,位置和尺寸之后,RenderTransform中的转换会得到应用,而LayoutTransform-Group中的转换将在WPF执行所有这些计算之前应用。

0

要旋转图像,最好的方法就是让WPF完成工作并使用LayoutTransform。

在XAML中,你必须与旋转的信息添加Image.LayoutTranform标签:

<Grid> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="50"/> 
     <RowDefinition/> 
    </Grid.RowDefinitions> 
    <Button Name="btnRotate" Click="btnRotate_Click">Rotate</Button> 
    <Image Grid.Row="1" Name="img" RenderTransformOrigin="0.5,0.5" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"> 
     <Image.LayoutTransform> 
      <RotateTransform Angle="0"/> 
     </Image.LayoutTransform> 
    </Image> 
</Grid> 

在C#中,你可以改变现在的点击动作旋转:

private void btnRotate_Click(object sender, RoutedEventArgs e) 
    { 
     double rotation = (double)img.LayoutTransform.GetValue(RotateTransform.AngleProperty); 
     rotation += 90; 
     img.LayoutTransform.SetValue(RotateTransform.AngleProperty, rotation % 360); 
    }