Search code examples
c#wpfxamlsilverlightexpression-blend

Set WPF Label Content Alpha Transparency instead of entire control Opacity


I am trying to Set a label's content to be invisible, so that I can overlay that on the content behind. For instance, the control's background is a solid color but, the text has a alpha transparency that allows me to see through the entire control (Like a photoshop trick). That way, dynamic content can be seen with a variable background. I apply this pattern with PNG files but, that obviously wont do when the content needs to change. A great example of this question (Since I am not very good at asking it) can be found here... but, of course, this is for css. (How to make "see through" text?) Any help on this would be appreciated


Solution

  • So I found a solution to this thing... The trick is to use Clip instead of OpacityMask.

    First look at the layout:

    <Grid Background="Red">
        <Border Background="White" Name="targetImage" VerticalAlignment="Center" Height="200"/>
    
        <Button VerticalAlignment="Bottom" Content="render" Click="ButtonBase_OnClick"></Button>
    </Grid>
    

    Here the grid with the red background can be used as your Background Image! The border inside it covers it with the white color. Then I put a button that removes the Text we want from border when pressed.

    here is the code for button click event:

    private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            Typeface face = new Typeface("Candara");
            FormattedText tx = new FormattedText("Hello", Thread.CurrentThread.CurrentUICulture, FlowDirection.LeftToRight, face, 70, Brushes.Black);
            Geometry textGeom = tx.BuildGeometry(new Point(0, 0));
            Rect boundingRect = new Rect(new Point(-100000, -100000), new Point(100000, 100000));
            RectangleGeometry boundingGeom = new RectangleGeometry(boundingRect);
            GeometryGroup group = new GeometryGroup();
            group.Children.Add(boundingGeom);
            group.Children.Add(textGeom);
            targetImage.Clip = group;   
    
    
        }
    

    It's basically creating a text! then we need to invert the mask. inverting is done using the help of boundingRect .

    Edit: Almost forgot. You can put all this logic inside a User control. and run this code everytime the Text property of your Usercontrol changes.

    have fun ;)