WPF TextBlock: How to evenly space displayed characters?

左心房为你撑大大i 提交于 2019-12-19 08:39:44

问题


I need to display a string with each character displayed every x pixels. (x is accross the whole string).

e.g.: "Hello" -> H at position (pixel) 0, e at position 50, l at 100, l at 150, o at 200.

Of course I could use a TextBlock for each character but it seems overkill.

TranslateTransform doesn't seem to do the trick: It offsets my characters relatively to the END of the previous character, which is not what I want.

TIA for your help.


回答1:


I don't believe there's an in-built abilty to do this in WPF, but I could be wrong.

The code below demonstrates how you could write your own control to do this for you. It isn't efficient, and it could do with tweaking, including more properties to control font etcetera, but you get the idea:

SpacedTextBlock.cs:

public class SpacedTextBlock : Control
{
    public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text",
        typeof(string),
        typeof(SpacedTextBlock));

    public string Text
    {
        get { return GetValue(TextProperty) as string; }
        set { SetValue(TextProperty, value); }
    }

    protected override void OnRender(DrawingContext drawingContext)
    {
        base.OnRender(drawingContext);

        if (Text != null)
        {
            var widthPerChar = ActualWidth / Text.Length;
            var currentPosition = 0d;

            foreach (var ch in Text)
            {
                drawingContext.DrawText(new FormattedText(ch.ToString(), CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface("Arial"), 12, Foreground), new Point(currentPosition, 0));
                currentPosition += widthPerChar;
            }
        }
    }
}

Window1.xaml:

<local:SpacedTextBlock Text="Hello"/>

Result:

alt text http://img199.imageshack.us/img199/8022/screenshotud.png




回答2:


I guess it depends on the details of your situation whether this will work or not. But could you just add spaces between each letter, and set the text alignment to be justified?

Unfortunately you don't get to set the # of pixels this way if that's what you need... but you can get even spacing this way. If this isn't just one spot on your window or is a little more complex with dynamic text... then you may want to look into a more elegant solution.



来源:https://stackoverflow.com/questions/1476311/wpf-textblock-how-to-evenly-space-displayed-characters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!