Qt 文字抗鋸齒

阿Hai發表於2024-09-21

1. 通常情況下, 在 paintEvent 中繪製文字時, 不管是否設定抗鋸齒選項, 都不會有明顯的鋸齒, 如下程式碼所示, Antialiasing/TextAntialiasing 對最終的效果沒有顯著影響.

    QFont ft = painter.font();
    ft.setFamily("PingFang SC");
    ft.setPixelSize(13);
    ft.setWeight(QFont::Medium);
    painter.setFont(ft);
    painter.setRenderHint(QPainter::Antialiasing, false);
    painter.setRenderHint(QPainter::TextAntialiasing, false);
    // painter.setRenderHint(QPainter::Antialiasing, true);
    // painter.setRenderHint(QPainter::TextAntialiasing, true);
    painter.drawText(0, 0, 200, 50, Qt::AlignCenter, "Test1234567890");

                

2. 某些情況下, 我們需要將資料預先繪製到快取圖片上(如多執行緒構建快取圖片), 再繪製到介面上時, 上述程式碼就有問題了

    if (image.isNull())
    {
        image = QImage(300, 300, QImage::Format_RGBA8888);
        image.fill(Qt::transparent);
        QPainter painter(&image);
        QFont ft = painter.font();
        ft.setFamily("PingFang SC");
        ft.setPixelSize(13);
        ft.setWeight(QFont::Medium);
        painter.setFont(ft);
        // painter.setRenderHint(QPainter::Antialiasing, false);
        // painter.setRenderHint(QPainter::TextAntialiasing, false);
        painter.setRenderHint(QPainter::Antialiasing, true);
        painter.setRenderHint(QPainter::TextAntialiasing, true);
        painter.drawText(0, 0, 200, 50, Qt::AlignCenter, "Test1234567890");
    }
    painter.drawImage(0, 0, image);

            

上述 image 是一個 QImage 物件, 我們啟用 Antialiasing/TextAntialiasing, 可以看到文字還是出現了明顯的鋸齒.

此時我們需要開啟字型的抗鋸齒選項, 才能避免出現這種現象:

    if (image.isNull())
    {
        image = QImage(300, 300, QImage::Format_RGBA8888);
        image.fill(Qt::transparent);
        QPainter painter(&image);
        QFont ft = painter.font();
        ft.setFamily("PingFang SC");
        ft.setPixelSize(13);
        ft.setWeight(QFont::Medium);
        ft.setStyleHint(QFont::AnyStyle, QFont::PreferAntialias);
        // ft.setStyleStrategy(QFont::PreferAntialias);
        painter.setFont(ft);
        painter.drawText(0, 0, 200, 50, Qt::AlignCenter, "Test1234567890");
    }
    painter.drawImage(0, 0, image);

              

透過設定 ft.setStyleHint(QFont::AnyStyle, QFont::PreferAntialias); 或 ft.setStyleStrategy(QFont::PreferAntialias); 之後, 可以看到, 文字鋸齒消失了.

相關文章