#560 – Using a Radial Gradient to Create a 3D Effect

You can use a radial gradient in WPF to create a 3D effect on a shape.  In the example below, we set up a gradient on a circle (Ellipse shape) to make the circle look like a 3D sphere.

Start by drawing a simple circle (Ellipse).

Now specify a radial gradient for the Fill property.

Next, click on the Gradient tool and then slide the radial gradient off-center, relative to the ellipse.

Finally, adjust the gradient so that the center starts out white and fades to a darker color at the edge of the gradient.  You can also enlarge the gradient so that its outer edge lines up with the outer edge of the ellipse.

Here’s the final result:

Advertisements

#557 – Using an Image As an Opacity Mask

You’ll typically use a gradient brush as an opacity mask, to change the opacity of a control gradually.

You can also use an image as an opacity brush, making various regions of the target control opaque or transparent depending on the opacity at the same spot in the image.

Below, I’ve created a smiley face image in Paint.NET.  I’ve made the background of the image transparent (shown in Paint.NET as a checkerboard).

Next I create a WPF project with a simple Image control.

    <Image Source="Images\Rocks2Small.jpg" Width="400"/>

Now we specify an OpacityMask for this Image.  But instead of using a LinearGradientBrush or RadialGradientBrush, we use an ImageBrush–a brush created from an image.

<Image Source="Images\Rocks2Small.jpg" Width="400">
    <Image.OpacityMask>
        <ImageBrush ImageSource="Images\FaceMask.png"/>
    </Image.OpacityMask>
</Image>

Using the second image as the opacity mask for the first means–the first image will be transparent wherever the second image is transparent.

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