如果渲染QString
s
超过rect.width()
. 目前我正在做:
inline void drawFadedLineText(QPainter* const painter, QRectF const& rect,
QColor const& color, QString const& s)
{
painter->setPen(color);
auto const fontMetrics(painter->fontMetrics());
if (fontMetrics.width(s) > rect.width())
{
QPixmap pixmap(rect.size().toSize());
pixmap.fill(Qt::transparent);
{
QPainter p(&pixmap);
p.setFont(painter->font());
p.drawText(0, fontMetrics.ascent(), s);
static QLinearGradient lg;
static bool init;
if (!init)
{
init = true;
lg.setStops(QGradientStops{
qMakePair(qreal(0), QColor(0, 0, 0, 238)),
qMakePair(qreal(1), QColor(0, 0, 0, 17))});
}
// else do nothing
static auto const margin(qreal(10));
auto const right(rect.width());
lg.setStart(right - margin, qreal(0));
lg.setFinalStop(right, qreal(0));
p.setCompositionMode(QPainter::CompositionMode_DestinationIn);
p.fillRect(QRectF(right - margin, 0, margin, rect.height()), lg);
}
painter->drawPixmap(rect.topLeft(), pixmap);
}
else
{
painter->drawText(QPointF(rect.left(),
rect.top() + fontMetrics.ascent()), s);
}
}
这种方法的问题是,需要一个额外的层(a QPixmap
),但我不能DestinationIn
直接将合成模式与文本一起使用,因为画家可能已经用一些背景绘制了,然后淡化文本会淡化那个以及。有没有更好的方法?