开发者

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>

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 cr开发者_JS百科op 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.


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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜