Clipping AdornerLayer

1k views Asked by At

I have a PanZoomImage class defined like this:

<Border Grid.Row="0" Name="border" ClipToBounds="True">
    <Canvas Name="canvas">
        <Image Name="image" RenderOptions.BitmapScalingMode="NearestNeighbor" Stretch="None" 
           Source="{Binding Path=Source}"
           MouseLeftButtonDown="image_MouseLeftButtonDown"
           MouseLeftButtonUp="image_MouseLeftButtonUp"
           MouseMove="image_MouseMove"
           MouseWheel="image_MouseWheel"
           Loaded="image_Loaded">
        </Image>
    </Canvas>
</Border>

Sometimes I want to display Adorners on the image so I have a property that gives me the AdornerLayer for the image:

public AdornerLayer Adorners
{
    get
    {
        return AdornerLayer.GetAdornerLayer(image);
    }
}

I use this property to add different adorners to the image. The problem is that when I pan or zoom the image, the aodrners are not clipped and are displayed outside the control that holds the PanZoomImage, like this: No clipping

I tried several solutions:

I tried setting ClipToBounds=True for the border, the canvas and the image.

I tried setting ClipToBounds=True for the AdornerLayer and for each Adorner individually.

I tried setting a Clip Geometry in Adorner's OnRender.

I also noticed there's a IsClipEnabled property to Adorner but when I tried setting it to true, I kept getting a NullReferenceException (even though the Adorner was definitely not null)...

Thanks!

2

There are 2 answers

0
Jiří Skála On

The IsClipEnabled property works. The NullPointerException is thrown if the adorned control has no parent. You have to place the control into some container before setting IsClipEnabled.

0
Andreas On

For me the secret source was to:

  1. Set IsClipEnabled=true on the Adorner
  2. Set ClipToBounds=true on the adorned element