WPF:如何避免图像超出 Canvas 的边界?
我有一个画布作为图像查看器。它的背景用于放置图像,我想在其上面放置另一个图像。所以,场景是这样的:
<Canvas Name="VisorCanvas" Height="514" Width="720">
<Canvas.Background>
<ImageBrush />
</Canvas.Background>
<Image Name="foreground" />
</Canvas>
我在代码后面(C#)动态插入图像。
问题是,如果图像太大,则图像会超出画布的边界。例如:我有一个不相关的背景图像,我想通过以下方式在“画布”面板内(在其背景顶部)显示一个正方形:
- 在任何情况下,都会调整正方形图像的大小。
- 如果它小于画布的尺寸,我就显示它。
- 如果它在任何尺寸(宽度或高度)上更大,我需要裁剪它或将图像的一部分设置为透明。这样做我实现了电视模式或类似的东西,因为图形总是看起来在画布“内部”(尽管一部分被裁剪)
我该怎么做?我尝试过:
- 使用 CroppedBitmap 裁剪图像,但它不准确。
- 要通过附加的 opacityMask 图像使用透明度,但我需要从原始图像创建一个蒙版位图(具有透明度),但我不知道该怎么做。
- 通过使用 RenderTargetBitmap 创建“照片”并用此方法的结果替换图像,但我做不到。
如果有人能阐明这一点,我将不胜感激。
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>
I insert images dynamically in code behind (C#).
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:
- In any case the square's image will be resized.
- if it's smaller than canvas's dimensions, I just show it.
- if it's bigger in whatever dimension (width or height), I need either to crop it or set transparent a part of image. Doing so I achieve a TV mode or something like this, since the figure will always seem "inside" the canvas (although a part is cropped)
How may I do that? I've tried:
- To crop the image by using CroppedBitmap but it's not accurate.
- To use transparency through an additional opacityMask image, but I'd need to create a mask bitmap (with transparency) from the original one and I don't know how to do that.
- To create a "photo" by using RenderTargetBitmap and replacing the image by the result of this method, but I couldn't.
I'd be grateful If someone could shed light on it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在
Canvas
元素中设置ClipToBounds="True"
,这将阻止图像超出画布的边界。您可能还需要考虑不使用
Image
元素。您可以使用Rectangle
,并将Fill
设置为ImageBrush
,因为您可以使用Viewbox
和>Viewport
属性来选择您想要源图像的哪一部分以及您想要的输出大小。 (将ViewportUnits
设置为Absolute
以精确控制绘制区域的尺寸。)Set
ClipToBounds="True"
in yourCanvas
element, and that will stop the image going beyond the canvas's borders.You might also want to consider not using an
Image
element. You could use aRectangle
with theFill
set to anImageBrush
because you can then use theViewbox
andViewport
properties to select which part of the source image you want, and the size of the output you want. (SetViewportUnits
toAbsolute
to take precise control over the dimensions of the painted area.)