开发者

In WPF, view a portion of an image

We have an image where we create view box coordinates that are topleft/bottom right points within the image that are setup to allow for viewing portions of an image at different times in our application. In WPF, how do we load an image, and with topleft/bottom right points within that image, only show the portion of the image within that 开发者_开发知识库view box?


You can do this with a CroppedBitmap:

<Image>
  <Image.Source>
    <CroppedBitmap Source="<path to source image>" SourceRect="20,20,50,50"/>
  </Image.Source>
</Image>

This will display the 50x50 region of the image starting at position (20,20)


Using a RenderTransform with a Clip works even better, because the CroppedBitmap is kinda immutable:

<Image x:Name="MyImage">
    <Image.RenderTransform>
        <TranslateTransform X="-100" Y="-100" />
    </Image.RenderTransform>
    <Image.Clip>
        <RectangleGeometry Rect="0 0 250 250" />
    </Image.Clip>
</Image>

This will display the image at offset (100, 100) with a size of (150, 150), so don't forget the rect must include the startoffsets.

Here's a method to calculate it in code:

public static void ClipImage(System.Windows.Controls.Image image, Rect visibleRect)
{
    image.RenderTransform = new TranslateTransform(-visibleRect.X, -visibleRect.Y);
    image.Clip = new RectangleGeometry
    {
        Rect = new Rect(
            0, 
            0, 
            visibleRect.X + visibleRect.Width, 
            visibleRect.Y + visibleRect.Height)
    };
}


It seems to me that you can make the image control a part of the viewbox as shown below:

<Viewbox Name="vBox" Stretch="None" HorizontalAlignment="Left" 
VerticalAlignment="Top" Height="50" Width="50">
<Image Name="ClippedImage" 
Source="{Binding NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True}" 
Stretch="None" />
</Viewbox>

This will give you a view box 50x50. obviously you can change the height and width to suit your needs. I use a scrollviewer to pan around the smaller viewbox.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜