Game Development Reference
In-Depth Information
A label has very few parts, it can be done with a background and the text. The background
maybeassimpleasacolorrectangle,itisbestwhenthebackgroundissettoautomatically
resize based on the content of the label. This is especially important when doing localiza-
tion for a game, as it will guarantee that regardless of the length of the text, it will always
have a background. One useful feature to implement in labels is the ability to specify the
text alignment within a label's bounds.
void label::Refresh()
{
math::vector2 textSize = GetTextSize();
m_textRectangle = math::rectangle::MakeRectangle(
m_rectangle.Left(),
m_rectangle.Top(),
m_rectangle.Left() + textSize.x(),
m_rectangle.Top() + textSize.y() );
align a(m_textRectangle, m_rectangle, m_alignment);
a.Apply();
}
math::vector2 GetTextSize() const
{
return math::vector2(m_font->MeasureString(m_text.c_str()));
}
We measure the size of the text, then place it at the origin of the viewport, then we run it
through the alignment helper to finalize the text positioning.
Drawing the label means drawing two things, the background and the text, we may option-
ally not use a background, which is useful in many situations.
void label::InternalDraw()
{
m_backgroundColor.A() = m_alpha;
m_foregroundColor.A() = m_alpha;
if ( m_showBackground )
{
m_spriteBatch->Draw(*m_core->GetBlackTexture()->GetView(),m_autoSize ? m_textRectangle : m_rectangle, nullptr,
m_backgroundColor);
}
m_font->DrawString(m_spriteBatch.get(), m_text.c_str(), m_textRectangle.Position(), m_foregroundColor, 0.f, math::vector4::Zero,
math::vector4::One, DirectX::SpriteEffects_None, 0.f);
}
Notice that depending on whether we have specified if the label should AutoSize we render
the background differently. When we AutoSize a label we draw the minimal encompassing
extents around the text, otherwise we will use the size as it was specified with SetSize .
Search WWH ::




Custom Search