WPF: How to avoid an image get out of Canvas's borders?

可紊 提交于 2020-05-12 21:04:52

问题


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.


回答1:


Set ClipToBounds="True" in your Canvas 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 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.)



来源:https://stackoverflow.com/questions/5275760/wpf-how-to-avoid-an-image-get-out-of-canvass-borders

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!