How can I get WPF's ClipToBounds to work?

后端 未结 2 1735
攒了一身酷
攒了一身酷 2021-01-18 06:07

I have an application that displays an image inside of an Image object in WPF. The image is contained in a control whose xaml looks like:



        
相关标签:
2条回答
  • 2021-01-18 06:39

    The above comment help me out. Nest one canvas in another, add ClipToBounds="True" to the parent and bind the nested height and width to the parent properties respectively.
    This way removes the need to perform transformations on the parent.

    <Canvas ClipToBounds="True" Name="Outer">
         <Canvas x:Name="Inner" 
             Height="{Binding ActualHeight, ElementName=Outer, Mode=OneWay}"
             Width="{Binding ActualWidth, ElementName=Outer, Mode=OneWay}" />
    </Canvas>
    
    0 讨论(0)
  • 2021-01-18 06:48

    Canvas is kind of unique in that it doesn't really participate in the layout system like other elements. It basically acts as an infinite size space with fixed position children so generally ignores clipping completely. I can't tell for sure without seeing more of the code but if you want to apply the clipping to the scaled object moving the scaling to a different element might do what you want. The simplest thing to do would be to wrap a Border around your Canvas and apply the ScaleTransform to that instead. The Border should give you better clipping behavior.

    <Border x:Name="border" Background="Black" ClipToBounds="True">
        <Canvas x:Name="imageHost">
        ...
        </Canvas>
    </Border>
    
    0 讨论(0)
提交回复
热议问题