具有不透明背景的 WPF 透明文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27941864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF transparent text with opaque background
提问by Torsten Crull
I need transparent text with opaque background with WPF/XAML. Is that possible?
我需要带有 WPF/XAML 的不透明背景的透明文本。那可能吗?
Here is an example, but I don't use css: css, transparent text with opaque background
这是一个例子,但我不使用 css: css, transparent text with opaque background
Maybe there is a manner in order to produce transparent text with opaque background with c#?
也许有一种方法可以使用 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>
回答by safi
U can make this by converting your text to Pathand then Make ClippingOn your white Rectanglewith that Path.
你可以通过将你的文本转换为Path然后Clipping在你的白色上Rectangle使用它来做到这一点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;
}
回答by PiotrWolkowski
You can set it using the Opacityproperty on the SolidColorBrush. It takes values from 0 to 1. Where 0is complete transparency and 1complete 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.
您可以使用设置它Opacity的属性SolidColorBrush。它采用从 0 到 1 的值。其中0是完全透明和1完全不透明。但是,如果您将文本设置为透明,那么您将看到的是文本框的背景。在示例中,我设置了部分不透明度,因此您可以看到文本呈灰色。
<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.
获得透明度并查看文本块下方控件背景的另一件事是设置透明的前景和部分透明的背景。

