github:https://github.com/coldfirehello/QtDemo.git
最近UI小哥哥检查界面效果,觉得头像显示不够清晰。
当前效果图:
竞品效果图:
原图:
1.当前效果图:
实现方法:通过样式表实现圆形头像和缩放效果。
实现代码:
QLabel styleSheetLabel;
styleSheetLabel.setFixedSize(40, 40);
styleSheetLabel.setStyleSheet(QString("QLabel{border-radius:20px;border-image:url(%1);}").arg(filePath));
分析:
原图确实很清晰,但是通过样式表处理后,图片比较模糊。
2.第一次优化效果图:
实现方法:使用QPainter在QBitmap上绘制圆形头像,用QPixmap实现缩放后头像。
实现代码:
头像缩放及圆角处理:
QPixmap pixmapToRound(const QPixmap &src, int radius)
{
if (src.isNull())
{
return QPixmap();
}
QSize size(2*radius, 2*radius);
QBitmap mask(size);
QPainter painter(&mask);
painter.setRenderHint(QPainter::Antialiasing);
painter.setRenderHint(QPainter::SmoothPixmapTransform);
painter.fillRect(0, 0, size.width(), size.height(), Qt::white);
painter.setBrush(QColor(0, 0, 0));
painter.drawRoundedRect(0, 0, size.width(), size.height(), radius, radius);
QPixmap image = src.scaled(size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
image.setMask(mask);
return image;
}
测试代码:
QLabel pixmapLabel;
pixmapLabel.setFixedSize(40, 40);
QPixmap pixmap(filePath);
pixmapLabel.setPixmap(pixmapToRound(pixmap, 20));
UI小哥哥:头像是清晰了很多,但是放大几倍后觉得圆角处理的像“啃过”似的(锯齿严重),不够圆滑。竞品效果很圆滑,你再想想办法吧。
对过来放大后效果:
我:那我再试试……
3.最终版效果:
放大后效果:
实现方法:使用QPainter在QPixmap上绘制缩放后的头像,用QPainter的裁剪方法(setClipPath)和QPainterPath实现缩放后头像。
实现代码:
UI小哥哥:我觉得效果没什么问题了,你是怎么实现的。
我:裁剪出一个圆形头像。
#include "hdIcon.h"
#include <QPainter>
HDIcon::HDIcon(QWidget *parent) : QLabel(parent)
{
}
HDIcon::~HDIcon()
{
}
void HDIcon::setIconInfo(const QString &filePath, const QSize &scaledSize, int radius)
{
QPixmap pixmap = pixmapToRound(filePath, scaledSize, radius);
if(!pixmap.isNull())
{
setPixmap(pixmap);
}
}
QPixmap HDIcon::pixmapToRound(const QString &filePath, const QSize &scaledSize, int radius)
{
QPixmap headPixmap(scaledSize);
QPixmap pixmap(filePath);
if(pixmap.isNull() && !scaledSize.isValid() && radius < 0)
{
headPixmap = QPixmap();
}
else
{
headPixmap.fill(Qt::transparent);
QPainter painter(&headPixmap);
QPainterPath painterPath;
QRect rect(0, 0, scaledSize.width(), scaledSize.height());
painterPath.addRoundedRect(rect, radius, radius);
painter.setRenderHint(QPainter::Antialiasing);
painter.setRenderHint(QPainter::SmoothPixmapTransform);
painter.setClipPath(painterPath);
painter.drawPixmap(rect, pixmap.scaled(scaledSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
}
return headPixmap;
}
测试代码:
HDIcon hdIcon;
hdIcon.setIconInfo(filePath, QSize(40, 40), 20);
小结:
圆形图像效果对比 | ||
实现方法 | 圆形效果 | 清晰度 |
样式表 | 放大后不圆滑(锯齿严重) | 模糊 |
QBitmap、QPainter、QPixmap | 放大后不圆滑(锯齿严重) | 清晰 |
QPainter、QPixmap、QPainterPath | 放大后圆滑 | 清晰 |
喜欢的点个好看吧,谢谢各位大佬捧场!