Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF TextBlock: How to evenly space displayed characters?

Tags:

wpf

textblock

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.

like image 920
Serge Wautier Avatar asked Jan 23 '23 04:01

Serge Wautier


1 Answers

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

like image 134
Kent Boogaart Avatar answered Feb 11 '23 23:02

Kent Boogaart