How to overlay a rectangle on an image in WPF

I want to place a static rectangle on top of the image.

The rectangle must be a percentage of the image size (eg 80%) regardless of the image size.

I tried to put the image in the canvas and as the Canvas background, but then I can't get the image to fill it.

<Canvas Grid.Row="1" Grid.Column="0">
    <Canvas.Background>
        <ImageBrush ImageSource="{Binding Path=Image1}"/>
    </Canvas.Background>
 </Canvas>

      

+2


source to share


2 answers


Place it on the grid and then place the rectangle in the same row and column. And use a converter to get 80% size.

XAML:

<Window.Resources>
    <local:RectangleSizeConverter x:Key="RectangleSizeConverter" />
</Window.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
    <Image x:Name="image" Grid.Row="0" Grid.Column="0" Source="C:\on.jpg" />
    <Rectangle Height="{Binding ElementName=image, Path=ActualHeight, Converter={StaticResource RectangleSizeConverter}}" 
               Width="{Binding ElementName=image, Path=ActualWidth, Converter={StaticResource RectangleSizeConverter}}" 
               Fill="Red" Opacity=".5" />
</Grid>

      



C # (converter):

public class RectangleSizeConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return System.Convert.ToDouble(value) * .8;
    }

    public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new System.NotImplementedException();
    }

    #endregion
}

      

+4


source


Here's how you can do it with pure XAML using a DrawingBrush to partially fill the overlapping rectangle:



<Grid>          
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
    <Image Source="http://sstatic.net/so/img/logo.png" Stretch="None" />
    <Rectangle>
        <Rectangle.Fill>
            <DrawingBrush Viewbox="0,0,1,1" ViewboxUnits="Absolute">
                <DrawingBrush.Drawing>
                    <GeometryDrawing Brush="#66FF0000">
                        <GeometryDrawing.Geometry>
                            <RectangleGeometry Rect="0,0,.9,.9" />
                        </GeometryDrawing.Geometry>
                    </GeometryDrawing>
                </DrawingBrush.Drawing>
            </DrawingBrush>
         </Rectangle.Fill>
     </Rectangle>
</Grid>

      

+3


source







All Articles