x1是1和7的最大理想宽度(也就是你想要保存的宽度); x2同理;
想在Qt实现九宫格切图,第一:需要先确定原来图片的像素大小,其次确定好四个角的宽度和高度,因为四个角是你所需要不变的部分。第二:则需要确定你所需要图片的像素大小,根据新图片的宽度以及高度,确定3, 4, 5, 6, 8几个部分scaled()所需伸缩变化大小。第三:根据之前所切的图片组合成一张你所需要的图片。
/*
* @brief:九宫格缩放图片
* @param: pixName[in] 原来图片的路径
* @param: x1[in] 左上角预设图片宽度
* @param: y1[in] 左上角预设图片高度
* @param: x2[in] 右上角预设图片宽度
* @param: y2[in] 左下角预设图片宽度
* @param: iNewPixWidth[in] 放大/缩小图片的宽度
* @param: iNewPixHeight[in] 放大/高度
* @return: QImage
*/
QImage FrameChange::framePix(const QString& pixName, int x1, int y1, int x2, int y2, int inewPixWidth, int inewPixHeight)
{
QPixmap* pix = new QPixmap(pixName);
//切割原图
QPixmap pix_1 = pix->copy(0, 0, x1, y1);
QPixmap pix_3 = pix->copy(pix->width() - x2, 0, x2, y1);
QPixmap pix_7 = pix->copy(0, pix->height() - y2, x1, y2);
QPixmap pix_9 = pix->copy(pix->width() - x2, pix->height() - y2, x2, y2);
QPixmap pix_2 = pix->copy(x1, 0, pix->width() - x1 - x2, y1);
QPixmap pix_4 = pix->copy(0, y1, x1, pix->height() - y1 - y2);
QPixmap pix_6 = pix->copy(pix->width() - x2, y1, x2, pix->height() - y1 - y2);
QPixmap pix_8 = pix->copy(x1, pix->height() - y2, pix->width() - x1 - x2, y2);
QPixmap pix_5 = pix->copy(x1, y1, pix->width() - x1 - x2, pix->height() - y1 - y2);
//进行伸缩变换
pix_2 = pix_2.scaled(iNewPixWidth- x1 - x2, y1, Qt::IgnoreAspectRatio);
pix_4 = pix_4.scaled(x1, iNewPixHeight- y1 - y2, Qt::IgnoreAspectRatio);
pix_5 = pix_5.scaled(iNewPixWidth- x1 - x2, iNewPixHeight- y1 - y2, Qt::IgnoreAspectRatio);
pix_6 = pix_6.scaled(x2, iNewPixHeight- y1 - y2, Qt::IgnoreAspectRatio);
pix_8 = pix_8.scaled(iNewPixWidth- x1 - x2, y2, Qt::IgnoreAspectRatio);
QImage resultPix(QSize(iNewPixWidth, iNewPixHeight), QImage::Format_ARGB32_Premultiplied);
QPainter painter(&resultPix);
//消除背景阴影(如果背景出现阴影则需要,反之不需要)
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setCompositionMode(QPainter::CompositionMode_Source);
painter.fillRect(QRect(0, 0, iNewPixWidth, iNewPixHeight), Qt::transparent);
painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
//组合碎片
if (!resultPix.isNull())
{
painter.drawPixmap(0, 0, pix_1);
painter.drawPixmap(x1, 0, pix_2);
painter.drawPixmap(iNewPixWidth- x2, 0, pix_3);
painter.drawPixmap(0, y1, pix_4);
painter.drawPixmap(x1, y1, pix_5);
painter.drawPixmap(iNewPixWidth- x2, y1, pix_6);
painter.drawPixmap(0, iNewPixHeight- y2, pix_7);
painter.drawPixmap(x1, iNewPixHeight- y2, pix_8);
painter.drawPixmap(iNewPixWidth- x2, iNewPixHeight- y2, pix_9);
painter.end();
}
return resultPix;
}