我找到了一种使用TextBlock类来设置字母间距的方法,因为它支持TranslateTransforms。PropertyChangedCallback
通过用自定义替换默认值TextBlock.TextProperty
,我们可以TranslateTransform
将TextBlock
.
这是我所做的完整的分步编码:
首先,我们创建一个自定义类并像这样继承TextBlock
:
using System.Windows.Controls;
namespace MyApp
{
class SpacedLetterTextBlock : TextBlock
{
public SpacedLetterTextBlock() : base()
{
}
}
}
然后,在 XAML 中,我们将 TextBlock 更改为我们的自定义类(可以在此处找到更多信息):
<Window x:Class="MyApp.MainWindow"
...
xmlns:app="clr-namespace:MyApp">
<Grid>
<app:SpacedLetterTextBlock>
Some Text
</app:SpacedLetterTextBlock>
</Grid>
</Window>
最后,在代码隐藏文件中的InitializeComponent()
方法之前,添加如下方法:.cs
OverrideMetadata
// This line of code adds our own callback method to handle any changes in the Text
// property of the TextBlock
SpacedLetterTextBlock.TextProperty.OverrideMetadata(
typeof(SpacedLetterTextBlock),
new FrameworkPropertyMetadata(null,
FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(OnTextChanged)
)
);
...并在每次更改时应用于TranslateTransform
每个字母TextProperty
:
private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
SpaceLettersOut(d);
}
// This method takes our custom text block and 'moves' each letter left or right by
// applying a TranslateTransform
private static void SpaceLettersOut(DependencyObject d)
{
SpacedLetterTextBlock thisBlock = (SpacedLetterTextBlock)d;
for (int i = 1; i <= thisBlock.Text.Length; i++)
{
// TranslateTransform supports doubles and negative numbers, so you can have
// whatever spacing you need - do see 'Notes' section in the answer for
// some limitations.
TranslateTransform transform = new TranslateTransform(2, 0);
TextEffect effect = new TextEffect();
effect.Transform = transform;
effect.PositionStart = i;
effect.PositionCount = thisBlock.Text.Length;
thisBlock.TextEffects.Add(effect);
if (effect.CanFreeze)
{
effect.Freeze();
}
}
}
注意事项:
首先,我是 WPF 和 C# 的完全新手,所以我的答案可能不是最干净的解决方案。如果您对如何改进此答案有任何意见,我们将不胜感激!
其次,我没有用大量TextBlock
元素测试过这个解决方案,并且(可能)TranslateTransform
对TextBlock.Text
.
最后,文本的任何正值TextBlock
超出范围。我认为您可以重新计算宽度,然后以编程方式放置它(?)X
TranslateTransform
TextBlock