XAML在ScrollViewer中将图像调整为页面大小

时间:2014-04-12 15:24:44

标签: xaml windows-runtime

我在Image内有ScrollViewer。有些图像太大而无法放入Page内。如何在首次显示时Image的尺寸缩小到Page尺寸?

<ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
    <Image Stretch="None" />
</ScrollViewer>

更新了答案

这是我根据Filip的答案而做的,而另一个他回答了类似的问题here

XAML:

<ScrollViewer x:Name="scrollViewer">
    <Image x:Name="image" Stretch="None" SizeChanged="ImageSizeChanged" />
</ScrollViewer>

代码背后:

private bool imageSizeSet;
private void ImageSizeChanged( object sender, SizeChangedEventArgs e )
{
    if( imageSizeSet || !( image.ActualWidth > scrollViewer.ViewportWidth ) && !( image.ActualHeight > scrollViewer.ViewportHeight ) )
    {
        return;
    }

    // If the image is larger than the screen, zoom it out.
    var zoomFactor = (float)Math.Min( scrollViewer.ViewportWidth / image.ActualWidth, scrollViewer.ViewportHeight / image.ActualHeight );
    scrollViewer.ZoomToFactor( zoomFactor );
    imageSizeSet = true;
}

1 个答案:

答案 0 :(得分:4)

<ScrollViewer
    x:Name="theScrollViewer"
    HorizontalScrollBarVisibility="Auto"
    VerticalScrollBarVisibility="Auto"
    SizeChanged="OnSizeChanged">
    <Image
        x:Name="theImage"
        Stretch="Uniform" />
</ScrollViewer>

private void OnSizeChanged(object sender, SizeChangedEventArgs args)
{
    theImage.Width = theScrollViewer.ViewportWidth;
    theImage.Height = theScrollViewer.ViewportHeight;
}