具有不透明背景的 WPF 透明文本 [英] WPF transparent text with opaque background

查看:43
本文介绍了具有不透明背景的 WPF 透明文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是一个例子,但我不使用 css:​​css,透明文本背景不透明

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

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

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>

推荐答案

您可以通过将您的文本转换为 Path 然后在您的白色 上制作 Clipping 来实现这一点>矩形与那个Path.

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

试试这个:

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

这篇关于具有不透明背景的 WPF 透明文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆