天天看點

Qt繪制文字輪廓

首先看一下使用Qt繪制文字輪廓效果:

Qt繪制文字輪廓

這裡使用 QPainter 中的 strokePath 函數實作文字輪廓的繪制。

  • void QPainter::strokePath(const QPainterPath &path, const QPen &pen)

    函數 strokePath 表示使用pen繪制一個路徑的輪廓。

    Draws the outline (strokes) the path path with the pen specified by pen

是以它不僅僅可以繪制文字的輪廓,也可以繪制其他圖形元素的輪廓。

上圖中的矩形框也同樣添加了輪廓線。

繪制部分完整代碼如下:

// 設定抗鋸齒
painter->setRenderHint(QPainter::Antialiasing);

// 設定字型
QFont font = painter->font();
font.setPixelSize(30);
painter->setFont(font);

// 确定位置
QFontMetrics metrics = painter->fontMetrics();
int width = metrics.width(m_sText);
int height = metrics.height();
int xPt = (this->rect().width() - width) / 2;
int yPt = (this->rect().height() - height) / 2 + height;

// 設定繪制路徑
QPainterPath path;
path.addText(xPt, yPt, font, m_sText);
path.addRect(QRect(xPt, yPt - height, width, height).adjusted(-10, -10, 10, 10));

// 添加輪廓
QPen pen;
pen.setWidth(4);
pen.setColor(QColor(255, 0, 0));
painter->strokePath(path, pen);

// 繪制
pen.setWidth(2);
pen.setColor(QColor(120, 120, 120));
painter->setPen(pen);
painter->drawPath(path);
           

作者:douzhq

個人部落格首頁:不會飛的紙飛機

文章同步頁:Qt繪制文字輪廓

繼續閱讀