#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!
Pingback: Dew Drop – May 11, 2012 (#1,325) | Alvin Ashcraft's Morning Dew
How about use Clip property to clip the image like:
myImage.Clip = new RectangleGeometry(new Rect(0, 0, 400, 267), 40, 40);
“The CornerRadius is calculated from the mid-line of the border, not from the outer edge. As a result, when you set the CornerRadius to 70 and BorderThickness to 50, the “ActualCornerRadius” is 70+50/2 = 95. So, to perfectly match the outer Border, the inner radius in your example should be 95-50 = 45.
And here is a general formula: Mask.CornerRadius = OuterBorder.CornerRadius – OuterBorder.BorderThickness / 2.”
Or you can simply set the border’s backgound to an ImageBrush that uses your image as its source…
This code rises a binding error (Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:(no path); DataItem=null; target element is ‘VisualBrush’ ; target property is ‘Visual’ (type ‘Visual’)”)