Search code examples
c#-4.0backgroundtransparencyuwpuwp-xaml

Is it possible to combine an ImageBrush with a LinearGradientBrush in UWP


I'm building a Planning Poker UWP app for fun. I can style the poker cards (currently implemented as Buttons, via the Background property) using either an ImageBrush or a LinearGradientBrush without any issue, but obviously I can only set one type of brush to that property.

I'd like to style the card with an image, which then had another brush (e.g. a LinearGradientBrush) over-layed on top, this other brush would naturally have some degree of transparency so that parts of the image could show through.

How would you do that?

For the actual poker card that the user sees - I can re-implement that fairly easily using a different control type (e.g. a UserControl that combined several controls, each with their own background) but there are other instances of use (i.e. showing a list of the available styles), so I wanted to see if there way another way before looking into writing a custom UserControl.


Solution

  • Button is a content control, you can put other xaml controls in the button's content, and set LinearGradientBrush for them. For example,you can set ImageBrush for the button's background property, in the meanwhile set LinearGradientBrush for a Rectangle inline.

    I'd like to style the card with an image, which then had another brush (e.g. a LinearGradientBrush) over-layed on top, this other brush would naturally have some degree of transparency so that parts of the image could show through.

    To meet your requirement, I wrote a code example as follows:

    <Button x:Name="BtnPoker" Padding="0">
        <Rectangle Width="200"
                   Height="300"
                   Margin="0"
                   Opacity="0.4">
            <Rectangle.Fill>
                <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                    <GradientStop Offset="0.0" Color="Yellow" />
                    <GradientStop Offset="0.25" Color="Red" />
                    <GradientStop Offset="0.75" Color="Blue" />
                    <GradientStop Offset="1.0" Color="LimeGreen" />
                </LinearGradientBrush>
            </Rectangle.Fill>
        </Rectangle>
        <Button.Background>
            <ImageBrush ImageSource="Assets\caffe.jpg" />
        </Button.Background>
    </Button>
    

    And the result:

    enter image description here