WPF TextBlock: How to evenly space displayed chara

2019-02-18 05:55发布

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.

标签: wpf textblock
2条回答
2楼-- · 2019-02-18 06:38

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.

查看更多
叼着烟拽天下
3楼-- · 2019-02-18 06:43

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

查看更多
登录 后发表回答