Specifying TextAlignment for Draw.Text()
Description
Is there a StringFormat like capability for this library? There are quite a number of strings I need to center no matter the length.
There isn't anything built in at the moment.
For the moment you'll have to roll your own logic to decide the left offset required. You will need to use the SixLabors.Fonts.TextMeasurer class to accomplish this.
You can see an example of using the TextMeasurer it in this blog post http://sixlabors.com/2017/04/08/watermarks/.
NOTE: I do plan on adding on alignment settings to TextGraphicsOptions in the future.
@tocsoft Yes, please; I am using TextMeasure to create a fitting image from a given text, but it only works well with default TextGraphicsOptions settings.
in versions > 1.0.0-alpha8-00061 you can now specify a TextAlignment on the TextGraphicsOptions that you can pass in to DrawText().
How it works:
If you specify text alignment but don't specify a WrapTextWidth then the alignment start from the location the text is drawn at. i.e. if right aligned text with WrapTextWidth == 0 (no wrapping) then the right hand edge of the text will be at the drawing location.
If you specify a WrapTextWidth > 0 then it will be ralative to a location between Location and location + WrapTextWidth. i.e. Location = (100, 100) and WrapTextWidth = 300 and TextAlignment == Center then the text will be rendered centered on (250, 100), or if TextAlignment == Right its right edge will be rendered from (400, 100).
Example of Center aligned text:
Variables in scope
string text = ".......";
Image<Rgba32> image = .....; // image class
Font font = ...; // font loaded;
Center aligned no wordwrap
Vector2 center = new Vector2(image.Width/2, 10); //center horizontally, 10px down
image.DrawText(text, font, NamedColors<Rgba32>.Black, center, new TextGraphicsOptions(true){
TextAlignment = TextAlignment.Center
});
Center aligned with wordwrap
float padding = 10f;
float textMaxWidth = image.Width - (padding * 2); // width of image indent left & right by padding
Vector2 topLeftLocation = new Vector2(padding, padding);
image.DrawText(text, font, NamedColors<Rgba32>.Black, topLeftLocation , new TextGraphicsOptions(true){
WrapTextWidth = textMaxWidth,
TextAlignment = TextAlignment.Center
});