WPF Rub out top image to reveal image underneath
As the title suggests, using WPF I want to have a scenario where I have a bitmap image with another bitmap overlayed on top of it and, using the mouse, "paint" over the t开发者_运维百科op bitmap so that it reveals the bitmap underneath. Is this just as simple as painting with a transparent brush? I have tried this to no avail but maybe I am missing something.
You can use a VisualBrush
to create an OpacityMask
. Here is a code example of a dark green rectangle being replaced by a light green one. Using this approach the two rectangles could be any elements including images.
<Grid MouseMove="Grid_MouseMove">
<Rectangle Fill="DarkGreen"/>
<Rectangle Fill="LightGreen">
<Rectangle.OpacityMask>
<VisualBrush Stretch="None" AlignmentX="Left" AlignmentY="Top">
<VisualBrush.Visual>
<Path Name="path" Stroke="Black" StrokeThickness="10"/>
</VisualBrush.Visual>
</VisualBrush>
</Rectangle.OpacityMask>
</Rectangle>
</Grid>
and here is the code-behind:
private void Grid_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
var point = e.GetPosition(sender as Grid);
if (lastPoint != nullPoint)
AddSegment(lastPoint, point);
lastPoint = point;
}
else
{
lastPoint = nullPoint;
}
}
private void AddSegment(Point point1, Point point2)
{
if (segments.Count == 0 || segments[segments.Count - 1].Point != point1)
segments.Add(new LineSegment(point1, false));
segments.Add(new LineSegment(point2, true));
var figures = new PathFigureCollection();
figures.Add(new PathFigure(new Point(), segments, false));
var geometry = new PathGeometry();
geometry.Figures = figures;
path.Data = geometry;
}
List<LineSegment> segments = new List<LineSegment>();
private static readonly Point nullPoint = new Point(-1, -1);
Point lastPoint = nullPoint;
精彩评论