WPF LayoutTransform(Scale)引发异常,因为图像的DesiredSize为NaN



我正在设置图像的ImageSource,如下所示:

Stream imageStreamSource = new FileStream(_filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource,BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
BitmapSource bmSrc = decoder.Frames[0];
bmSrc.Freeze();
ImageSource = bmSrc;

图像在Scrollviewer中使用ScaleTransform(LayoutTransform)
需要LayoutTransform来更新ScrollViewers的内容大小
我想将图像缩放到滚动查看器的父级(边界)的大小:

double horizontalAspectRatio = gridBounds.Width / image.Width;
double verticalAspectRatio = gridBounds.Height / image.Height;
if (horizontalAspectRatio > verticalAspectRatio) {
     scaleTransformImage.ScaleX = scaleTransformImage.ScaleY = verticalAspectRatio;
     MessageBox.Show("to height");
} else {
     scaleTransformImage.ScaleX = scaleTransformImage.ScaleY = horizontalAspectRatio;
     MessageBox.Show("to width");
}

之后抛出InvalidOperationException,它表示测量图像的布局需要DesireSize不为NaN
我试着像这样手动测量和排列图像:

image.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
image.Arrange(new Rect(0d, 0d, gridBounds.Width, gridBounds.Height));

但它似乎没有效果
我刚开始学习Transforms,还没有太多知识。。。。

只要您没有显式设置Image控件的WidthHeight属性,它们的值将为NaN,并且纵横比计算将失败:

double horizontalAspectRatio = gridBounds.Width / image.Width;
double verticalAspectRatio = gridBounds.Height / image.Height;

您可以使用图像的ActualWidthActualHeight,或者如果尚未布局,则使用其Source:的WidthHeight

double horizontalAspectRatio = gridBounds.Width / image.Source.Width;
double verticalAspectRatio = gridBounds.Height / image.Source.Height;

相关内容

  • 没有找到相关文章

最新更新