#556 – Clipping to a Border Using an Opacity Mask
May 11, 2012 5 Comments
When you specify a border radius for a Border element, the content within the Border is not automatically clipped to the new rounded interior.
<Border BorderBrush="Black" BorderThickness="3" Margin="10" Width="400" Height="267" CornerRadius="40" > <Image Source="Images\Rocks2Small.jpg"/> </Border>
If you want to clip against the Border, you can specify an opacity mask that is a visual brush bound to the visual of a second Border element that overlays the Image control. This will cause any portion of the Image control that falls outside the boundaries of the inner Border to use an opacity of 0.0.
<Border BorderBrush="Black" BorderThickness="3" Margin="10" Width="400" Height="267" CornerRadius="40" > <Grid> <Border Name="myBorder" CornerRadius="40" Background="White" Margin="1"/> <Image Source="Images\Rocks2Small.jpg" Margin="1"> <Image.OpacityMask> <VisualBrush Visual="{Binding ElementName=myBorder}"/> </Image.OpacityMask> </Image> </Grid> </Border>
Thanks to fellow Minnesotan, Chris Cavanagh, for an explanation of how to do this!