【问题标题】:wpf resize image automatically [duplicate]wpf自动调整图像大小[重复]
【发布时间】:2020-09-14 04:00:55
【问题描述】:

这几天我一直在努力想弄清楚为什么我的控件不想调整大小。

例如,我在一个可调整大小的窗口中将 background.png 作为窗口背景。窗口成功重新调整大小,并且背景根据需要填充了整个窗口。但图像不会!两个图像都是 .png,它们都是相同的 dpi,并且都具有相同的分辨率。

ActuatorUC 中的图像应该直接与背景对齐,因为它有透明部分。

MainWindow.xaml ->

<Window.Background>
    <ImageBrush ImageSource="Resources/background.png"></ImageBrush>
</Window.Background>

<Grid Name="mainGrid">
    <tc:ActuatorUC x:Name="act1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"  />
</Grid>

ActuatorUC.xaml ->

<Canvas Name="canvas" >
</Canvas>

ActuatorUC.xaml.cs ->

private void LoadImage(string imageName )
{

this.canvas.Children.Clear();

Image image = new Image();

string newImageName = "pack://application:,,,/Resources/" + imageName + ".png";

image.Source = (new ImageSourceConverter()).ConvertFromString(newImageName) as ImageSource;
image.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
image.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;

this.canvas.Children.Add(image);

}

动态添加的图片有效,它会显示但不会随父画布调整大小。

我已经进行了大量搜索,但我无法弄清楚这一点。我很确定这是我对 wpf 的一些简单或误解。不幸的是,这些图片是专有的,所以我无法将它们添加到此帖子中。

提前致谢。

【问题讨论】:

  • Canvas 永远不会调整其子级的大小,只会忽略任何 Horizo​​ntalAlignment 或 VerticalAlignment。请改用网格。 ImageBrush 应将其 Stretch 属性设置为 Fill(不过这是默认设置)。

标签: c# wpf image xaml code-behind


【解决方案1】:

感谢克莱门斯的评论,我将其修复如下。

Window.Xaml ->

<Window.Background>
    <ImageBrush ImageSource="Resources/background.png"></ImageBrush>
</Window.Background>

<Grid Name="mainGrid">
    <tc:ActuatorUC x:Name="act1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"  />
</Grid>

ActuatorUC.Xaml ->

<Grid Name="grid" >

</Grid>

ActuatorUc.Xaml.cs ->

private void LoadImage(string imageName )
{

this.canvas.Children.Clear();

Image image = new Image();

string newImageName = "pack://application:,,,/Resources/" + imageName + ".png";

image.Stretch = Stretch.Fill;
image.Source = (new ImageSourceConverter()).ConvertFromString(newImageName) as ImageSource;

this.canvas.Children.Add(image);

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 2022-07-04
    相关资源
    最近更新 更多