WPF:如何避免图像脱离Canvas的边界? [英] WPF: How to avoid an image get out of Canvas's borders?
问题描述
我有一个画布作为图像查看器。它的背景用于放置图片,我想在其上方放置另一张图片。因此,情况是这样的:
I have a canvas as an image viewer. Its background is used to place an image and I'd like to put another image on top of it. So, the scenario is like this:
<Canvas Name="VisorCanvas" Height="514" Width="720">
<Canvas.Background>
<ImageBrush />
</Canvas.Background>
<Image Name="foreground" />
</Canvas>
我在(C#)后面的代码中动态插入图像。
I insert images dynamically in code behind (C#).
问题是,如果图像太大,则图像超出了Canvas的边界。例如:我有一个不相关的背景图像,我想通过以下方式在画布面板内(在其背景上方)显示一个正方形:
The problem is that if the image is too big, then the image goes beyond the Canvas's borders. For instance: I have an irrelevant background image and I want to show a square inside the Canvas panel (on top of its background) through the following way:
- 在任何情况下都将调整正方形图像的大小。
- 如果它比画布的尺寸小,我只显示它。
- 如果它是无论尺寸(宽度或高度)是否更大,我都需要对其进行裁剪或将图像的一部分设置为透明。这样做是为了达到电视模式或类似的效果,因为人物总是看起来在画布的内部(尽管一部分被裁剪了)
我该怎么做?我尝试过:
How may I do that? I've tried:
- 使用CroppedBitmap裁剪图像,但这并不准确。
- 要通过其他opacityMask图像使用透明度,但是我需要从原始图像中创建一个具有透明度的蒙版位图,并且我不知道该怎么做。
- 要通过使用RenderTargetBitmap创建一个照片,并用此方法的结果替换图像,但是我做不到。
d如果有人可以阐明它,将不胜感激。
I'd be grateful If someone could shed light on it.
推荐答案
设置 ClipToBounds = True
在您的 Canvas
元素中,这将阻止图像超出画布的边界。
Set ClipToBounds="True"
in your Canvas
element, and that will stop the image going beyond the canvas's borders.
您可能还想考虑不使用 Image
元素。您可以使用矩形
,并将填充
设置为 ImageBrush
,因为您随后可以使用 Viewbox
和 Viewport
属性来选择所需的源图像部分,以及您想要的输出大小。 (将 ViewportUnits
设置为 Absolute
可以精确控制绘制区域的尺寸。)
You might also want to consider not using an Image
element. You could use a Rectangle
with the Fill
set to an ImageBrush
because you can then use the Viewbox
and Viewport
properties to select which part of the source image you want, and the size of the output you want. (Set ViewportUnits
to Absolute
to take precise control over the dimensions of the painted area.)
这篇关于WPF:如何避免图像脱离Canvas的边界?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!