SFML community forums
General => Feature requests => Topic started by: tobybear on January 20, 2012, 11:08:02 pm
-
I quickly thought about vertical and horizontal alignment of text (left, center, right / top, center, bottom) and fiddled around with the sf::Text class.
Here is what I came up with:
In Text.hpp I added some more style flags for alignment:
enum Style
{
Regular = 0, ///< Regular characters, no style
Bold = 1 << 0, ///< Bold characters
Italic = 1 << 1, ///< Italic characters
Underlined = 1 << 2, ///< Underlined characters
AlignHCenter = 1 << 3,
AlignHRight = 1 << 4,
AlignVCenter = 1 << 5,
AlignVBottom = 1 << 6
};
And in Text.cpp I added the following lines to the end of UpdateGeometry():
// Recompute alignment
bool alignHCenter = (myStyle & AlignHCenter) != 0;
bool alignHRight = (myStyle & AlignHRight) != 0;
bool alignVCenter = (myStyle & AlignVCenter) != 0;
bool alignVBottom = (myStyle & AlignVBottom) != 0;
float w = 0.0f;
float h = 0.0f;
if (AlignHRight) w = myBounds.Left + myBounds.Width;
else if (AlignHCenter) w = 0.5f * (myBounds.Left + myBounds.Width);
if (AlignVBottom) h = myBounds.Top + myBounds.Height;
else if (AlignVCenter) h = 0.5f * (myBounds.Top + myBounds.Height);
for (unsigned int i = 0; i < myVertices.GetVertexCount(); i++)
{
myVertices[i].Position.x -= w;
myVertices[i].Position.y -= h;
}
This allows you to output text aligned relatively to its x/y position in both vertical and horizontal directions by using SetStyle.
For example for right and bottom aligned text:
mytext.SetStyle(AlignHRight | AlignVBottom);
I don't know if this is of use for anyone, just wanted to share this if maybe someone wondered as well if or how this could be done. :-)
-
I think it can be misleading: it aligns the text within its own bounding box, the effects are very limited. People often want to align a text within an external container.
-
You are right that this only aligns relative to the text itself - as this is what I was needing :) I often want to output a centered or right aligned dynamic text string at a certain x,y position at this allows me to do that. But I also wrote some lines to allow the alignment settings within a bounding box/area, which also works well.
However this is just my personal extension (own text class) I made for my convenience and it probably wouldn't make sense to add this to the current SFML base - it was rather just a post to show how something like this could be done if needed.
-
I think the optimal solution would be having the text default size being its boundaries, but providing some SetSize function to change it. That way it would work for all cases, wouldn't it?