WPF Rounded Corners – and holes!

UPDATE: Silverlight 3 joins in the fun!

After my enormously successful WPF – Easy rounded corners for anything post(really!), I’ve had some questions about cropping corners of an image with its own transparency.

Since we’re using an OpacityMask, you can do far more than define basic on/off geometry.  There’s nothing stopping you using an image as part of the mask too…

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Grid HorizontalAlignment="Center" VerticalAlignment="Center">
      <TextBlock FontSize="128" HorizontalAlignment="Center" VerticalAlignment="Center">hello world!</TextBlock>
      <Grid HorizontalAlignment="Center" VerticalAlignment="Center">
          <Border Name="mask" CornerRadius="20" Background="White">
              <Border.OpacityMask>
                  <ImageBrush ImageSource="SampleAlpha.png" Stretch="UniformToFill"/>
              </Border.OpacityMask>
          </Border>
          <Image Source="e:\Scribble\temp\SampleAlpha.png">
              <Image.OpacityMask>
                  <VisualBrush Visual="{Binding ElementName=mask}"/>
              </Image.OpacityMask>
          </Image>
      </Grid>
  </Grid>
</Page>

Here’s the result:

image

Click here or the image above to try it out.  Notice as you resize the window the clipped corners maintain the same radius…

kick it

2 Comments

Leave a comment