[英]How to create a border for the text in the TextBlock?
我想為 TextBlock 中的文本創建一個邊框。
我嘗試放置陰影,但遇到了問題。 問題在於DropShadowPanel 。 我已經報告了這個問題
所以我需要一個替代方法來為 TextBlock 中的文本創建邊框。
作為參考,我希望文本看起來像這樣:
注意:需要 Windows 周年更新 (10.0.14393.0) 才能正確支持此效果。
UWPCommunityToolkit 將通過更新修復DropShadowPanel 的此問題,但我們可以通過為 DropShadowPanel 添加“HorizontalAlignment="Left"”來手動修復該問題。
使用Microsoft.Toolkit.Uwp.UI.Controls
<controls:DropShadowPanel BlurRadius="3" ShadowOpacity="1" OffsetX="0" OffsetY="0" Color="Black">
<TextBlock FontSize="42" Text="Vijay Nirmal" Foreground="White"/>
</controls:DropShadowPanel>
由於您遇到了 DropShadowPanel 的問題,我猜您想要文本的陰影,而不是邊框。
如果是這種情況,您可以執行以下操作:
<TextBlock Text="My text" Foreground="Black" RenderTransformOrigin="0.5,0.5" >
<TextBlock.RenderTransform>
<CompositeTransform TranslateX="1" TranslateY="1"/>
</TextBlock.RenderTransform>
</TextBlock>
<TextBlock Text="My text" Foreground="White" />
這將創建陰影效果。
我想我有你想要的。 您的 XAML 中仍然需要兩個 TextBlock。
<Grid x:Name="grid" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<!--TextBlock that will receive the shadow-->
<TextBlock FontSize="46" Text="My text" Foreground="White" x:Name="shadowTextBlock" />
<!--Let this TextBlock foreground black just for design time-->
<TextBlock FontSize="46" Text="My text" Foreground="Black" x:Name="foregroundTextBlock"/>
</Grid>
然后你需要在 page_loaded 中添加以下代碼:
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
// Set the right color to the foreground text
this.foregroundTextBlock.Foreground = this.shadowTextBlock.Foreground;
var compositor = ElementCompositionPreview.GetElementVisual(this.grid).Compositor;
var spriteVisual = compositor.CreateSpriteVisual();
spriteVisual.Size = this.grid.RenderSize.ToVector2();
var dropShadow = compositor.CreateDropShadow();
dropShadow.Mask = this.shadowTextBlock.GetAlphaMask();
dropShadow.Color = Colors.Black;
dropShadow.Offset = new Vector3(0, 0, -50);
spriteVisual.Shadow = dropShadow;
ElementCompositionPreview.SetElementChildVisual(this.shadowTextBlock, spriteVisual);
}
結果真的很像你的例子:
<Grid HorizontalAlignment="Left">
<TextBlock Text="TextBlock" TextWrapping="Wrap" FontSize="36" FontWeight="Bold" Foreground="#FF88BCCD" OpacityMask="Black" />
<Border BorderBrush="#FF0B232F" BorderThickness="2" />
</Grid>
另外,在這里檢查這個鏈接,它有你需要的一切,甚至更多:
你甚至不需要網格來放置它們。只需將 TextBlock 放在 Border 控件中:
<Border BorderBrush="Black" BorderThickness="2">
<TextBlock Text="TextBlock" FontSize="12" Foreground="Black" />
</Border>
這應該夠了吧。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.