Skip to content

Commit

Permalink
libgui|Font: Rasterizing a line of text onto an image
Browse files Browse the repository at this point in the history
  • Loading branch information
skyjake committed May 18, 2013
1 parent 99d3aa2 commit f386b1e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
15 changes: 15 additions & 0 deletions doomsday/libgui/include/de/gui/font.h
Expand Up @@ -23,8 +23,10 @@
#include <de/Rule>
#include <de/Rectangle>
#include <de/String>
#include <de/Vector>

#include <QFont>
#include <QImage>

#include "libgui.h"

Expand Down Expand Up @@ -55,6 +57,19 @@ class LIBGUI_PUBLIC Font
*/
Rectanglei measure(String const &textLine) const;

/**
* Rasterizes a line of text onto a 32-bit RGBA image.
*
* @param textLine Text to rasterize.
* @param foreground Text foreground color.
* @param background Background color.
*
* @return
*/
QImage rasterize(String const &textLine,
Vector4ub const &foreground = Vector4ub(255, 255, 255, 255),
Vector4ub const &background = Vector4ub(255, 255, 255, 0)) const;

Rule const &height() const;
Rule const &ascent() const;
Rule const &descent() const;
Expand Down
21 changes: 21 additions & 0 deletions doomsday/libgui/src/font.cpp
Expand Up @@ -20,6 +20,8 @@

#include <de/ConstantRule>
#include <QFontMetrics>
#include <QImage>
#include <QPainter>

namespace de {

Expand Down Expand Up @@ -81,6 +83,25 @@ Rectanglei Font::measure(String const &textLine) const
return Rectanglei::fromQRect(d->metrics->boundingRect(textLine));
}

QImage Font::rasterize(String const &textLine,
Vector4ub const &foreground,
Vector4ub const &background) const
{
Rectanglei bounds = measure(textLine);

QImage img(QSize(bounds.width(), bounds.height()), QImage::Format_ARGB32);

QColor bgColor(background.x, background.y, background.z, background.w);
img.fill(bgColor.rgba());

QPainter painter(&img);
painter.setFont(d->font);
painter.setPen(QColor(foreground.x, foreground.y, foreground.z, foreground.w));
painter.setBrush(bgColor);
painter.drawText(0, d->ascentRule->valuei(), textLine);
return img;
}

Rule const &Font::height() const
{
return *d->heightRule;
Expand Down

0 comments on commit f386b1e

Please sign in to comment.