QT 从ttf文件中读取图标

最近在做项目时,遇到需要显示一些特殊字符的需求,这些特殊字符无法从键盘敲出来,于是乎,发现可以从字体库文件ttf中读取显示。

参考博客:QT 图标字体类IconHelper封装支持Font Awesome 5-优快云博客

该博客封装的很不错,值得一看!

一、下载ttf文件

Font Awesome,一套绝佳的图标字体库和CSS框架

解压出来后,通过如下网站可以在线查看键值对照关系

Iconfont Previewiconfont preview for web, Momo's Blog, LuckyMomoicon-default.png?t=O83Ahttps://blog.luckly-mjw.cn/tool-show/iconfont-preview/index.html很好玩的一个网站!

就可以看到该字体库解析出来的很多图标了。

这里请看图片中红色圆圈全中的 bug 图标,如果需要读取他,那么请记住他的编码:&#xf188

注意,在代码中,我们用的是16进制方式,即:0xf188

在windows环境,右键字体,选择预览,即可看到字体名称

字体名称 字体文件名 是必须要知道的!

二、编码

新建QT项目,然后添加资源文件,将tts文件添加到资源文件中!

1.初始化字体后,就可以使用这个字体了

QFontDatabase::addApplicationFont("字体文件名");    // fontawesome-webfont.ttf
QFont iconFont = QFont("字体名称");    // FontAwesome

2.从字体库中获取图标,返回QPixmap

QPixmap IconHelper::getPixmap(const QColor &color, const QChar &str,
                              quint32 size, quint32 pixWidth, quint32 pixHeight, int flags)
{
    QPixmap pix(pixWidth, pixHeight);
    pix.fill(Qt::transparent);

    QPainter painter;
    painter.begin(&pix);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
    painter.setPen(color);


    iconFont.setPixelSize(size);
    painter.setFont(iconFont);

    painter.drawText(pix.rect(), flags, str);
    painter.end();

    return pix;
}

如果想要QImage,或者需要将图标保存为本地图片,则将QPixmap转为QImage后再保存本地即可。

IconHelper iconHelper("FontAwesome", "fontawesome-webfont.ttf");
QPixmap pixmap = iconHelper.getPixmap(QColor(0, 0, 0), QChar(0xf188), 300, 300, 300);
QImage iamge = pixmap.toImage();     // 转为 QImage
iamge.save("文件路径/文件名字.png");    // 保存为本地图片 

3.可以直接给部件设置背景图

void IconHelper::setIcon(QLabel *lab, const QChar &str, quint32 size)
{
    iconFont.setPixelSize(size);
    lab->setFont(iconFont);
    lab->setText(str);
}

4.测试1,给按钮设置背景图标为篮球,图标编码为 0xf17d

int size = 100;                                                             
int width = 100;                                                            
int height = 100;  
                                                         
IconHelper iconHelper("FontAwesome", "fontawesome-webfont.ttf");            
QWidget *w = new QWidget;                                                   
w->setFixedSize(width*3, height*3); 
                                        
QPushButton *btn = new QPushButton(w);                                      
btn->setFixedSize(width, height);   
                                        
iconHelper.setIcon(btn, QChar(0xf17d), size);  
                             
QHBoxLayout *hLayout = new QHBoxLayout(w);                                  
hLayout->addWidget(btn);                                                    
w->setLayout(hLayout);    
                                                  
w->show();                                                                  

5.测试2,给QLabel设置背景图标为虫子,图标编码为 0xf188

int size = 300;                                                                           
int width = 300;                                                                          
int height = 300;    
                                                                     
IconHelper iconHelper("FontAwesome", "fontawesome-webfont.ttf");                          
QPixmap p = iconHelper.getPixmap(QColor(0, 0, 0), QChar(0xf188), size, width, height);    

QWidget *w = new QWidget;                                                                 
w->setFixedSize(p.size()); 
                                                               
QLabel label(w);                                                                          
label.setFixedSize(p.size());                                                             
label.setPixmap(p);  
                                                                     
QHBoxLayout *hLayout = new QHBoxLayout(w);                                                
hLayout->addWidget(&label);                                                               
w->setLayout(hLayout);  
                                                                  
w->show();                                                                                

三、代码汇总

iconhelper.h

#ifndef ICONHELPER_H
#define ICONHELPER_H

#include <QtCore>
#include <QtGui>
#if (QT_VERSION > QT_VERSION_CHECK(5,0,0))
    #include <QtWidgets>
#endif


//图形字体处理类
class IconHelper : public QObject
{
    Q_OBJECT

public:
    explicit IconHelper(QString fontName, QString fontFileName, QObject *parent = nullptr);
    ~IconHelper() override;

    void setIcon(QLabel *lab, const QChar &str, quint32 size = 12);
    void setIcon(QPushButton *btn, const QChar &str, quint32 size = 12);
    QPixmap getPixmap(const QColor &color, const QChar &str, quint32 size = 12,
                      quint32 pixWidth = 15, quint32 pixHeight = 15, int flags = Qt::AlignCenter);

private:
    QFont iconFont;             // 图形字体
};
#endif // ICONHELPER_H

iconhelper.cpp

#include "iconhelper.h"

IconHelper::IconHelper(QString fontName, QString fontFileName, QObject *parent) : QObject(parent)
{
    // 判断图形字体是否存在,不存在则加入
    QFontDatabase fontDb;
    if (!fontDb.families().contains(fontName)) {
        // 从资源文件中读取ttf文件
        int fontId = QFontDatabase::addApplicationFont(QString(":/image/%1").arg(fontFileName));
        QStringList fontName = QFontDatabase::applicationFontFamilies(fontId);
        if (0 == fontName.count()) {
            qDebug() << QString("load fontFileName error").arg(fontFileName);
        }
    }


    if (fontDb.families().contains(fontName)) {
        iconFont = QFont(fontName);
#if (QT_VERSION >= QT_VERSION_CHECK(4, 8, 0))
        iconFont.setHintingPreference(QFont::PreferNoHinting);
#endif

    } else {    // 容错处理,如果字体加载失败,则使用默认字体
        QFont f;
        iconFont = f;
    }
}

IconHelper::~IconHelper()
{

}

void IconHelper::setIcon(QLabel *lab, const QChar &str, quint32 size)
{
    iconFont.setPixelSize(size);
    lab->setFont(iconFont);
    lab->setText(str);
}

void IconHelper::setIcon(QPushButton *btn, const QChar &str, quint32 size)
{
    iconFont.setPixelSize(size);
    btn->setFont(iconFont);
    btn->setText(str);
}

QPixmap IconHelper::getPixmap(const QColor &color, const QChar &str,
                              quint32 size, quint32 pixWidth, quint32 pixHeight, int flags)
{
    QPixmap pix(pixWidth, pixHeight);
    pix.fill(Qt::transparent);

    QPainter painter;
    painter.begin(&pix);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
    painter.setPen(color);


    iconFont.setPixelSize(size);
    painter.setFont(iconFont);

    painter.drawText(pix.rect(), flags, str);
    painter.end();

    return pix;
}

当根据大小获取到图标QPixmap后,就可以根据具体需要添加到相应的部件进行显示了!

完!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cpp_learners

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值