【问题标题】:Can I make QPainter fonts operate in the same units as everything else?我可以让 QPainter 字体以与其他字体相同的单位运行吗?
【发布时间】:2014-02-21 04:53:20
【问题描述】:

我从这个开始

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 的字体大小已正确更新,如 qWarning 行所示,但文本绘制得非常非常大。我认为这是因为 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?

【问题讨论】:

    标签: qt fonts


    【解决方案1】:

    您只需撤消画家上的任何“疯狂”缩放。

    // 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();
    

    【讨论】:

    • 这正是我试图避免的那种解决方案。看起来很hacky。为什么目标应该有“合理”的大小?下面都是向量和贝塞尔曲线,对吧?
    • @spraff 你玩你的手。这可能是本机或 3rdparty 字体系统的限制。这一堆代码所做的就是改变转换矩阵,这在底层是相当微不足道的。我不认为这很奇怪,除了你必须对矩形尺寸更聪明(我已经“把它平方”)
    猜你喜欢
    • 1970-01-01
    • 2011-09-09
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    • 1970-01-01
    • 2013-04-25
    • 2012-01-22
    相关资源
    最近更新 更多