Torsten Crull
Torsten Crull

Reputation: 133

WPF transparent text with opaque background

I need transparent text with opaque background with WPF/XAML. Is that possible?

Here is an example, but I don't use css: css, transparent text with opaque background

Maybe there is a manner in order to produce transparent text with opaque background with c#?

The background should be an Image, I tried it with a Canvas:

<Grid>
    <!-- shows only a black box, but should show red text on black background-->
    <Canvas Width="100" Height="20" Background="Red"/>
    <TextBlock Text="My text" Foreground="#00000000" Background="#FF000000"/>
</Grid>

Upvotes: 3

Views: 8064

Answers (2)

safi
safi

Reputation: 879

U can make this by converting your text to Path and then Make Clipping On your white Rectangle with that Path.

Try this:

<Grid Grid.Row="1">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto" />
                        <RowDefinition />
                    </Grid.RowDefinitions>

                    <TextBox x:Name="textToMask" TextChanged="textToMask_TextChanged" />
                    <Rectangle Grid.Row="1" x:Name="target" Fill="Yellow"/>
</Grid>

c# code

private void textToMask_TextChanged(object sender, TextChangedEventArgs e)  
{  
    Typeface face = new Typeface("Candara");  
    FormattedText tx = new FormattedText(textToMask.Text, 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);  
    target.Clip = group;  
} 

Upvotes: 1

PiotrWolkowski
PiotrWolkowski

Reputation: 8782

You can set it using the Opacity property on the SolidColorBrush. It takes values from 0 to 1. Where 0 is complete transparency and 1 complete opacity. But if you set the text transparent then what you will see is the background of the text box. In the example I've set partial opacity so you can see the text is greyish.

<TextBlock Text="Test" Background="Red" Width="100" Height="100">
    <TextBlock.Foreground>
        <SolidColorBrush Opacity="0.25" Color="Black"/>
    </TextBlock.Foreground>
</TextBlock>

Other thing to get the transparency and see the background of the control beneath the text block is to set transparent foreground and partially transparent background.

Upvotes: 3

Related Questions