有时候我们需要在不裁剪图片的情况下,显示图片指定的区域,qt中会有两种方法:
第一种使用qss来实现。
第二种使用绘制事件来实现。
原图:
现在我们需要显示它的中心位置,但是显示区域跟原图的长宽都不一样,宽度小于我们要显示的宽度,高度又要大于我们显示的高度,这个时候需要根据宽度比例放大图片,然后根据宽度比例计算y的位置,从y的位置取中间的区域。
qss实现:
m_btn = new QPushButton(this);
m_btn->resize(392,220); //显示区域
QPixmap pixmap(“/home/yjd/yjd/test/MypixPos/2.jpg”); //使用QPixmap或者QImage来获取图片的宽高。
int y = (pixmap.height()392.00/pixmap.width() - 220)/2pixmap.width()/392.00;//计算y的位置
QString pix = “border-image:url(/home/yjd/yjd/test/MypixPos/2.jpg)”;
QString pixstyle = QString(“%1 %2 0 %3 0”).arg(pix).arg(y).arg(y);//qss的这种方式是取图片距离上、右、下、左的的位置。
m_btn->setStyleSheet(pixstyle);
绘制事件实现:
QPainter p(this);
QPixmap pixmap(“/home/yjd/yjd/test/MypixPos/2.jpg”);
pixmap = pixmap.scaled(392,392.00/pixmap.width()*pixmap.height());//按照宽度等比例放大
p.drawPixmap(QRect(0,0,392,220),pixmap,QRect(0,(pixmap.height() - 220)/2,392,220));//第一个Rect是显示区域,第二个Rect是取图片中哪块区域。
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
m_btn = new QPushButton(this);
m_btn->resize(392,220);
// m_btn->setStyleSheet("background-image: url(/home/yjd/yjd/test/MypixPos/1.jpg);"
// "background-repeat:no-repeat;"
// "background-position:center;"
// "background-origin:border;");
QPixmap pixmap("/home/yjd/yjd/test/MypixPos/2.jpg");
int y = (pixmap.height()*392.00/pixmap.width() - 220)/2*pixmap.width()/392.00;
qWarning()<<"------------"<<pixmap.height()<<pixmap.width()<<y;
QString pix = "border-image:url(/home/yjd/yjd/test/MypixPos/2.jpg)";
QString pixstyle = QString("%1 %2 0 %3 0").arg(pix).arg(y).arg(y);
m_btn->setStyleSheet(pixstyle);
m_lab = new QLabel(this);
m_lab->setGeometry(0,230,392,400*392.00/225);
m_lab->setStyleSheet("border-image:url(/home/yjd/yjd/test/MypixPos/2.jpg)");
}
Widget::~Widget()
{
delete ui;
}
void Widget::paintEvent(QPaintEvent *event)
{
QPainter p(this);
QPixmap pixmap("/home/yjd/yjd/test/MypixPos/2.jpg");
pixmap = pixmap.scaled(392,392.00/pixmap.width()*pixmap.height());
p.drawPixmap(QRect(0,0,392,220),pixmap,QRect(0,(pixmap.height() - 220)/2,392,220));
}