Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Image as Background with Opacity Mask

Tags:

c#

wpf

xaml

I haven't been able to get this to work, but this is what I envision:

Essentially, I want to have a control in WPF where the background is set to a left aligned image with an opacity mask that fades the right side of the image out into transparency (so that the parent's background color shows through)

Is this type of thing possible? Here's what I've tried:

<DockPanel x:Name="ContentPanel" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
    <DockPanel.Background>                    
      <ImageBrush ImageSource="test.jpg" Stretch="None" AlignmentX="Left" AlignmentY="Center" />
    </DockPanel.Background>
    <DockPanel.OpacityMask>
      <LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">
        <GradientStop Color="Black" Offset="0"/>
        <GradientStop Color="White" Offset="0.5"/>
      </LinearGradientBrush>
    </DockPanel.OpacityMask>
</DockPanel>
like image 463
Andrew Burgess Avatar asked Mar 31 '11 19:03

Andrew Burgess


2 Answers

This example should get you started.

<Grid>
  <Grid.Resources>
    <Image x:Key="myImage" Source="test.jpg">
      <Image.OpacityMask>
        <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5" >
          <GradientStop Offset="0.0" Color="#00000000" />
          <GradientStop Offset="1.0" Color="#FF000000" />
        </LinearGradientBrush>
      </Image.OpacityMask>
    </Image>
    <VisualBrush x:Key="myBrush"  Visual="{StaticResource myImage}"/>
  </Grid.Resources>

  <DockPanel x:Name="ContentPanel" Width="550"
             HorizontalAlignment="Left"
             Background="{StaticResource myBrush}"/>
</Grid>
like image 115
Dave White Avatar answered Oct 20 '22 02:10

Dave White


You could also use a partially transparent bitmap (png). That way you can have more complex transparency effects than just a gradient.

like image 1
Emond Avatar answered Oct 20 '22 02:10

Emond