WPF TextBlock: how to display displayed characters evenly?

I need to display a string with every character displayed every x pixels. (x over the entire line).

for example: "Hello" → H at position (pixel) 0, e at position 50, l at 100, l at 150 o and 200.

Of course, I could use a TextBlock for each character, but that seems redundant.

TranslateTransform doesn't seem to do the trick: it shifts my characters relative to the END of the previous character, which I don't want.

TIA for your help.

+4
source share
2 answers

I do not believe that WPF has a built-in ability to do this, but I could be wrong.

The code below demonstrates how you can write your own control to do this for you. This is inefficient, and it could be related to customization, including more properties for controlling the font, etc., 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

+6
source

I think it depends on the details of your situation, whether it will work or not. But can you just add spaces between each letter and set the alignment of the text?

Unfortunately, you cannot set # pixels this way if that is what you need ... but you can get a uniform distance that way. If it's not just one spot on your window or a bit more complicated with dynamic text ... then you might want to take a look at a more elegant solution.

+2
source

All Articles