#556 – Clipping to a Border Using an Opacity Mask

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"/>

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" >
        <Border	Name="myBorder" CornerRadius="40" Background="White" Margin="1"/>
	<Image Source="Images\Rocks2Small.jpg" Margin="1">
	        <VisualBrush Visual="{Binding ElementName=myBorder}"/>

Thanks to fellow Minnesotan, Chris Cavanagh, for an explanation of how to do this!


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

5 Responses to #556 – Clipping to a Border Using an Opacity Mask

  1. Pingback: Dew Drop – May 11, 2012 (#1,325) | Alvin Ashcraft's Morning Dew

  2. Milo says:

    How about use Clip property to clip the image like:
    myImage.Clip = new RectangleGeometry(new Rect(0, 0, 400, 267), 40, 40);

  3. CornerRadius says:

    “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.”

  4. MarkF says:

    Or you can simply set the border’s backgound to an ImageBrush that uses your image as its source…

  5. WPF developer says:

    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’)”)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: