我可以让QPainter字体与其他所有字体一样运行吗?

时间:2014-02-20 15:50:36

标签: qt fonts

我从这个

开始
void draw_text (QPainter & p, const QString & text, QRectF target)
{
    float scale = calculate_font_scale (p, text, target); // about 0.0005

    QFont f = p .font ();
    float old_size = f .pointSizeF ();
    f .setPointSizeF (old_size * scale);
    p .setFont (f);

    // this prints the new font size correctly
    qWarning ("old: %f, new: %f", old_size, p .font () .pointSizeF ());

    // but that doesn't seem to affect this at all
    p .drawText (position, text);
}

QPainter的字体大小已经正确更新,正如q警告线所示,但文字吸引了很多,很大。我认为这是因为QPainter坐标系已经放大了很多并it seems setPointSizeF only works with sizes of at least 1。通过眼睛看起来字体是一个“单位”高,所以我会买那个解释,虽然它是愚蠢的。

我尝试使用setPixelSize代替,虽然p.fontMetrics().boundingRect(text)产生了一个看上去很清晰的答案,但它是以像素单位给出的。 上述函数的一个要求是文本的边界矩形相对于target参数水平和垂直居中,这是一个非常不同的坐标,所以算术不再有效,文本在屏幕外绘制数英里。

我希望能够任意变换坐标系,如果在这一点上,一个“单位”是一千个像素高而我在0.03x0.03单位框中绘制文本然后我想要字体到显然是高30像素,但我需要一直以常规单位计算我的所有几何,我需要fontMetrics::boundingRect在这些相同的通用单位。

有什么方法可以解决这个问题,还是我必须通过像素计算来安抚字体API?

1 个答案:

答案 0 :(得分:0)

你只需撤消任何"疯狂"缩小那里画家。

// Save the state
p.save();
// Translate the center of `target` to 0,0.
p.translate(-target.center());
// Scale so that the target has a "reasonable" size
qreal dim = 256.0;
qreal sf = dim/qMin(target.height(), target.width());
p.scale(sf, sf);
// Draw your text
p.setPointSize(48);
p.drawText(QRectF(dim, dim), Qt::AlignCenter | Qt::WordWrap, text);
// Restore the state
p.restore();