c# - 从位图图像裁剪图像

标签 c# wpf image

我正在尝试在 Image 控件中显示图像的固定部分。 Source 是来自磁盘或 Web 资源的 BitmapImage,并且是异步加载的。

我尝试使用CroppedImage

<UserControl.Resources>
    <CroppedBitmap x:Key="croppedImage" Source="{Binding Image}" SourceRect="20 46 273 202"/>
</UserControl.Resources>
...
<Image x:Name="TemplateImage" Height="202" Width="273" HorizontalAlignment="Left" Source="{StaticResource croppedImage}"/>

尝试创建 CroppedBitmap 时,这会产生 XamlParseException
我也在后面的代码中尝试过这个(C#)

new CroppedBitmap(Image, new System.Windows.Int32Rect(20, 46, 273, 202))

从网络资源加载时给我一个ArgumentException,表明该值超出了预期范围。我想这是由于图像尚未加载,因此没有大小。

有没有一种方法可以实现此目的(不一定使用 CroppedImage),而无需预加载图像?

顺便说一句:直接将 BitmapImage 作为源提供给 Image 控件效果很好,但当然这不会进行裁剪。

最佳答案

您可以使用带有 ImageBrush 填充的矩形来代替图像控件,并根据需要设置 View 框:

<UserControl.Resources>
    <ImageBrush x:Key="croppedImage" ImageSource="{Binding Image}"
                ViewboxUnits="Absolute" Viewbox="20,46,273,202"/>
</UserControl.Resources>
...
<Rectangle Height="202" Width="273" Fill="{StaticResource croppedImage}"/>

关于c# - 从位图图像裁剪图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19598833/

相关文章:

c# - 绑定(bind)到 TabControl SelectedIndex

java - 循环 256*256*256 颜色,使得颜色逐渐变化并且相似的色调在循环的后续迭代中不会重复?

html - 强制 Firefox 在 CSS 指定的尺寸内呈现空图像

html - 如何在预设图像中嵌入图像或视频

c# - .NET 的离线同步选项

c# - 加入4个词典

c# - 在 WPF DataGrid 中使用 Enter 键作为 Tab

c# - 将字符串格式化为电子邮件地址

c# - 文本框只读

wpf - 在 WPF 中为 ToolWindow 添加图标