qt把正方形图片修改成圆形图片

1.这种方式好用。

QPixmap UBUserOnlineStatusWidget::PixmapToRound(const QPixmap &src, int radius)
{
    if (src.isNull()) {
        return QPixmap();
    }

    QPixmap pixmapa(src);
    QPixmap pixmap(radius,radius);
    pixmap.fill(Qt::transparent);
    QPainter painter(&pixmap);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
    QPainterPath path;
    path.addEllipse(0, 0, radius, radius);
    painter.setClipPath(path);
    painter.drawPixmap(0, 0, radius, radius, pixmapa);

    return pixmap;
}

2.这种方式不知道为啥有锯齿,所以不推荐使用

QPixmap UBUserOnlineStatusWidget::PixmapToRound(const QPixmap &src, int radius)
{
    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);
    image.setMask(mask);
    return image;
}

3.调用方式

QPixmap pix2(QString(":/images/picGirl.png"));
QPixmap fitpixmap_userIcon=pix2.scaled(64, 64, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
fitpixmap_userIcon = PixmapToRound(fitpixmap_userIcon,32);

 

你可能感兴趣的:(qt把正方形图片修改成圆形图片)