限制ScaleTransform到最大高度和宽度

时间:2017-12-08 15:41:47

标签: c# wpf image scaletransform

有没有办法将ScaleTransform限制为最大高度和宽度?

我有Viewbox,后台Image设置为“无”。在此Viewbox中,我还ItemsControlCanvas上展示了较小的图片。由于背景图像可以由操作员选择,因此图像的像素大小可能会有所不同,因此操作员需要能够相应地缩放较小的图像。

但是如果缩放因子在中等大小的背景图像上设置得非常大,或者背景图像的尺寸很小,ItemsControl图像最终会溢出容器并阻止其他功能。

那么如何设置ScaleTransform的限制?

XAML:

<Viewbox Grid.Column="1">
    <Grid>
        <Image Source="{Binding Path=BackgroundImage}" Stretch="None" />
        <ItemsControl ItemsSource="{Binding Path=ThrusterCollection}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <Canvas />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemContainerStyle>
                <Style TargetType="{x:Type ContentPresenter}">
                    <Setter Property="Canvas.Bottom" Value="{Binding Path=CanvasYPosition}" />
                    <Setter Property="Canvas.Left" Value="{Binding Path=CanvasXPosition}" />
                    <Setter Property="LayoutTransform">
                        <Setter.Value>
                            <ScaleTransform ScaleX="{Binding Path=ParentRovIllustration.ThrusterImageScale}" 
                                            ScaleY="{Binding Path=ParentRovIllustration.ThrusterImageScale}" />
                        </Setter.Value>
                    </Setter>
                    <Setter Property="ContentTemplate">
                        <Setter.Value>
                            <DataTemplate>
                                <Image Source="{Binding Path=ThrusterImage}" />
                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </ItemsControl.ItemContainerStyle>
        </ItemsControl>
    </Grid>
</Viewbox>

截图:

enter image description here

1 个答案:

答案 0 :(得分:0)

基于Clemens&#39;评论,在代码中做限制工作正常。我只计算了滑块的最大缩放值,基于最小缩放到背景图像宽度一半的较小图像(推进器)。这最终成了我的解决方案。

C#:

private string _backgroundImageFilePath;
public string BackgroundImageFilePath {
    get { return _backgroundImageFilePath; }
    set {
        SetNotify(ref _backgroundImageFilePath, value);
        try {
            BackgroundImage = new BitmapImage(new Uri(BackgroundImageFilePath));
        }
        catch (FileNotFoundException) {
            BackgroundImage = ImageNotFoundBitmapImage;
        }
        catch (Exception) {
            BackgroundImage = ImageInvalidBitmapImage;
        }
        ThrusterImageMaximumScale = BackgroundImage.Width / (2 * RovIllustrationThruster.VerticalThrusterBitmapImage.Width);
        ThrusterImageMaximumScale = Math.Round(ThrusterImageMaximumScale, 1);
        if (ThrusterImageScale > ThrusterImageMaximumScale) {
            ThrusterImageScale = ThrusterImageMaximumScale;
        }
        ConfigurationHandler.IsDirty = true;
    }
}