具有不透明背景的 WPF 透明文本

本文关键字:WPF 透明 文本 背景 不透明 | 更新日期: 2023-09-27 18:37:25

我需要具有不透明背景的透明文本和WPF/XAML。这可能吗?

这是一个示例,但我不使用css:css,具有不透明背景的透明文本

也许有一种方法可以使用 c# 生成具有不透明背景的透明文本?

背景应该是图像,我用画布尝试过:

<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>

具有不透明背景的 WPF 透明文本

您可以使用

SolidColorBrush上的 Opacity 属性进行设置。它采用从 0 到 1 的值。0是完全透明和完全不透明1。但是,如果您将文本设置为透明,那么您将看到的是文本框的背景。在示例中,我设置了部分不透明度,以便您可以看到文本是灰色的。

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

获取透明度并查看文本块下方控件背景的另一件事是设置透明前景和部分透明背景。

您可以通过

将文本转换为Path然后使用该Path在白色Rectangle上制作Clipping来做到这一点。

试试这个:

<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# 代码

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;  
}