我有一个WPF .xaml文件,其中包含一个图像框架元素,该元素绑定到我的C#代码中的BitmapSource . 目前,我正在对我的位图(即512px)的图像宽度和高度进行硬编码,并且我已指定框架元素不会拉伸图像 . 因此,如果我的窗口大于位图,则图像似乎浮动在窗口的边界内 . 但是,我想要的是位图宽度和高度自动绑定到.xaml窗口的宽度和高度 . 因此,当我调整窗口大小时,位图会随之重新调整大小 . 我不是简单地希望图像被“拉伸”...而是,我希望位图的宽度和高度与包含它的窗口相匹配 . 我不完全确定如何做到这一点,但我会发布到目前为止的设置 .
在我的.xaml文件中,我有我的Image框架元素(注意:渲染转换只是沿着水平轴翻转图像):
<Image Source="{Binding WpfPreview}" Name="VectorPreview" Stretch="None" Width="{Binding Xres}" Height="{Binding Yres}" RenderTransformOrigin="0.5,0.5">
<Image.RenderTransform>
<ScaleTransform ScaleY="-1"/>
</Image.RenderTransform>
</Image>
然后我的C#代码中包含以下代码:
protected BitmapSource wpfPreview;
public BitmapSource WpfPreview
{
get { return wpfPreview; }
set
{
wpfPreview = value;
NotifyPropertyChanged("WpfPreview");
}
}
protected static int xres = 512;
public int Xres
{
get { return xres; }
set
{
xres = value;
NotifyPropertyChanged("Xres");
UpdateBitmapPreview();
}
}
protected static int yres = 512;
public int Yres
{
get { return yres; }
set
{
yres = value;
NotifyPropertyChanged("Yres");
UpdateBitmapPreview();
}
}
protected GDI.Bitmap gdiPreviewImage = new GDI.Bitmap(xres, yres);
public void UpdateBitmapPreview()
{
if(gdiPreviewImage.Width != xres || gdiPreviewImage.Height != yres) gdiPreviewSurface = new GDI.Bitmap(xres, yres);
using (var graphics = GDI.Graphics.FromImage(gdiPreviewImage))
{
graphics.Clear(Color.White);
graphics.ResetTransform();
currentSlicer.DrawBitmapPreview(graphics, PreviewOptions);
}
WpfPreview = Imaging.CreateBitmapSourceFromHBitmap(
gdiPreviewImage.GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions()
);
}
2 回答
你基本上想在调整大小时保持纵横比吗?我认为这些属性可以解决这个问题 . 将ClipToBounds设置为true,将
Stretch
设置为Uniform
.那么,在这一点上将宽度和高度直接绑定到窗口的宽度和高度会不会更简单?