Using brushes in WPF you can paint surfaces with patterns, images, colors, and gradients. One brush that is particularly useful is the VisualBrush. This brush paints an area with other visual objects, allowing elements to be “mirrored”.
The effect of reflection is easily achieved using a VisualBrush. With just a few lines of XAML we can reproduce this effect.
For this example, we will reflect a standard image. The XAML for this is simply:
Now let’s work on the reflection. First we will create a border element with the same dimensions as our image. This will provide us with a shape we can apply our visual brush to. To make sure the reflection is placed under the image, we will place both elements in a StackPanel. By default, a StackPanel stacks elements vertically. We will also set the border's background to “Red” so that we can test that things are rendering properly.
When compiled, you should see the following:
Before we can add the reflection we need to name our image so that we can reference it. For the sake of this example, we’ll name our image “myVisual”. We do this simply by adding x:Name=”myVisual” to the Image tag:
Now it’s time to add the magic. To reflect the original image onto our border element, we will remove the red background and replace it with a VisualBrush referencing our image. We do this by “binding” our visual brush to the image using the namespace we created, “myVisual”. The syntax to support this binding is as follows:
We have now mirrored our image by “painting” it onto the border element. When compiled, you should see two images:
To make our example look more like it is being reflected, we will flip the visual brush vertically.
To flip the visual brush we will apply a ScaleTransform and set the Y-axis scaling to “-1”. To correctly position the visual brush we need to set the center of the brush to match the center of our image. Since our image is 400x300, our brush’s center coordinates will be 400 divided by 2, or 200, on the x-axis and 300 divided by 2, or 150, on the y-axis. This results in a relative center point (200,150).
Our mirrored image now looks more like a reflection:
To finish the effect, we will set the border's Opacity and apply an OpacityMask so that the border element containing the visual brush fades into the background. For a final bit of polish, we will also add a border to our image and apply a linear gradient to the background of the main window. This complete, our final coded solution appears as follows:
When compiled, we have our final image.
댓글 영역