Fit Image in canvas using WPF
I have canvas with child images. Here is my XAML:
<Canvas x:Name="ImageArea" ClipToBounds="True">
<Image x:Name="BigImage" RenderTransformOrigin="0.5,0.5">
<Image.RenderTransform>
<TransformGroup>
<RotateTransform x:Name="ImageRotateTransform" Angle="0"/>
<ScaleTransform x:Name="ImageScaleTra开发者_JAVA百科nsform" ScaleX="1" ScaleY="1"/>
<TranslateTransform x:Name="ImageTranslateTransform" X="0" Y="0"/>
</TransformGroup>
</Image.RenderTransform>
</Image>
</Canvas>
I want to fit this image in canvas with this code:
var fitSize = Math.Max(BigImage.ActualHeight, BigImage.ActualWidth);
var targetSize = Math.Min(ImageArea.ActualHeight, ImageArea.ActualWidth);
var ratio = targetSize / fitSize;
ImageScaleTransform.ScaleX = ImageScaleTransform.ScaleY = ratio;
ImageTranslateTransform.X =
fitSize == BigImage.ActualWidth ?
0 : ImageArea.ActualWidth / 2 - BigImage.ActualWidth*ratio / 2;
ImageTranslateTransform.Y =
fitSize == BigImage.ActualHeight ?
0 : ImageArea.ActualHeight / 2 - BigImage.ActualHeight * ratio / 2;
This code computes scale ratio, then tries to center image depending of it size.
The problem is that X and Y coordinates of translate transform are computed right but image not positioned as expected (only small part of image visible in bottom down of the canvas). If set RenderTransformOrigin to 0,0
image positioned normal.
Where am I mistaken?
The problem is that the Image
is no longer positioned in the upper-left hand corner of the Canvas
after scaling and so the translation offsets don't appear to be working.
Here is a XAML-only fragment based on your question that has a red Rectangle
and we've done nothing more than manually set the scale factors to one and a half instead of one:
<Grid>
<Canvas x:Name="ImageArea" ClipToBounds="False" Background="Gray" Width="200" Height="200">
<Rectangle x:Name="BigImage" RenderTransformOrigin="0.5,0.5" Width="100" Height="100" Fill="Red">
<Rectangle.RenderTransform>
<TransformGroup>
<RotateTransform x:Name="ImageRotateTransform" Angle="0"/>
<ScaleTransform x:Name="ImageScaleTransform" ScaleX="1.5" ScaleY="1.5"/>
<TranslateTransform x:Name="ImageTranslateTransform" X="0" Y="0"/>
</TransformGroup>
</Rectangle.RenderTransform>
</Rectangle>
</Canvas>
</Grid>
Which produces this result:
This happens because of the RenderTransformOrigin
setting. You can leave the property unset or use the value "0,0"
to keep the upper-left hand corner firmly seated while you scale it.
use a Grid, its relative. Canvas is absolute positioning.
精彩评论