我有一个小问题,我有一个群组项,我想为它设置一个背景图片,它应该按比例缩放但默认情况下从左上角显示图像,我希望图像居中显示。
这里是一张插图,进一步解释我的问题。(灰色部分是剪辑的部分)
我有以下XAML代码:
<Image Source="/url/to/image.jpg" Stretch="UniformToFill"/>
我有一个小问题,我有一个群组项,我想为它设置一个背景图片,它应该按比例缩放但默认情况下从左上角显示图像,我希望图像居中显示。
这里是一张插图,进一步解释我的问题。(灰色部分是剪辑的部分)
我有以下XAML代码:
<Image Source="/url/to/image.jpg" Stretch="UniformToFill"/>
我成功解决了我的问题,我将图片放大到超出其所在容器的大小,并将其垂直居中对齐。
<Grid HorizontalAlignment="Left" Width="250" Height="125">
<Image Source="/url/to/image.jpg" Stretch="UniformToFill" Height="250" Margin="0" VerticalAlignment="Center"/>
</Grid>
图片的溢出是不可见的 :)
如果源图像的大小事先未知,我必须使用不同的技巧:
<Border Width="250" Height="250">
<Border.Background>
<ImageBrush ImageSource="/url/to/image.jpg"
Stretch="UniformToFill"/>
</Border.Background>
</Border>
我为Silverlight/Windows Phone编写了一个行为,用于处理类似的情况。 我需要展示的图片可能更大或更高,而我必须将其显示在正方形中。
该行为计算容器和图片的宽度/高度比例。 根据哪个最大/最高,我调整Image控件的大小以与父控件具有这种裁剪效果。
以下是与我的行为一起使用的示例XAML。
<Border Height="150" Width="150">
<Image Source="{Binding BitmapImage}" Stretch="UniformToFill"
HorizontalAlignment="Center" VerticalAlignment="Center">
<i:Interaction.Behaviors>
<b:FillParentBehavior />
</i:Interaction.Behaviors>
</Image>
</Border>
以下是C#代码的一部分。完整的代码可以在此处找到:FillParentBehavior.cs
double width = this.AssociatedObject.Width;
double height = this.AssociatedObject.Height;
var parentSize = new Size(this.parent.ActualWidth, this.parent.ActualHeight);
var parentRatio = parentSize.Width / parentSize.Height;
// determine optimal size
if (this.AssociatedObject is Image)
{
var image = (Image)this.AssociatedObject;
if (image.Source is BitmapImage)
{
var bitmap = (BitmapImage)image.Source;
var imageSize = new Size(bitmap.PixelWidth, bitmap.PixelHeight);
var imageRatio = imageSize.Width / imageSize.Height;
if (parentRatio <= imageRatio)
{
// picture has a greater width than necessary
// use its height
width = double.NaN;
height = parentSize.Height;
}
else
{
// picture has a greater height than necessary
// use its width
width = parentSize.Width;
height = double.NaN;
}
}
}
this.AssociatedObject.Width = width;
this.AssociatedObject.Height = height;