Qt使用九宫格原理缩放图片

9宫格缩放规则如下:
1、将一张图分割成9块
2、四个角(1,3,7,9)在缩放的时候是保持大小不变
3、图块2,8仅当宽度变化时缩放宽度。
4、图块4,6仅当高度变化时缩放高度。
5、图块5当图片大小发生变化,宽度和高度都进行缩放。

Qt使用九宫格原理缩放图片_第1张图片

/*
**  功能             : 九宫格图处理
**  picName          : 图片名字
**  iHorzSplit       : 四个角上格子的宽度
**  iVertSplit       : 四个角上格子的高度
**  DstWidth         : 整个图片缩放的宽度
**  DstWidth         : 整个图片缩放的高度
**  返回值           : 处理完成的图片
*/
QPixmap* NinePatch(QString& picName,int iHorzSplit,int iVertSplit, int DstWidth, int DstHeight)
{
    QPixmap* pix = new QPixmap(picName);
 
    int pixWidth = pix->width();
    int pixHeight = pix->height();
 
    QPixmap pix_1 = pix->copy(0, 0, iHorzSplit, iVertSplit);
    QPixmap pix_2 = pix->copy(iHorzSplit, 0, pixWidth-iHorzSplit*2, iVertSplit);
    QPixmap pix_3 = pix->copy(pixWidth-iHorzSplit, 0, iHorzSplit, iVertSplit);
 
    QPixmap pix_4 = pix->copy(0, iVertSplit, iHorzSplit, pixHeight-iVertSplit*2);
    QPixmap pix_5 = pix->copy(iHorzSplit, iVertSplit, pixWidth-iHorzSplit*2, pixHeight-iVertSplit*2);
    QPixmap pix_6 = pix->copy(pixWidth-iHorzSplit, iVertSplit, iHorzSplit, pixHeight-iVertSplit*2);
 
    QPixmap pix_7 = pix->copy(0, pixHeight-iVertSplit, iHorzSplit, iVertSplit);
    QPixmap pix_8 = pix->copy(iHorzSplit, pixHeight-iVertSplit, pixWidth-iHorzSplit*2, pixWidth - iHorzSplit*2);
    QPixmap pix_9 = pix->copy(pixWidth-iHorzSplit, pixHeight-iVertSplit, iHorzSplit, iVertSplit);
 
    pix_2 = pix_2.scaled(DstWidth-iHorzSplit*2,iVertSplit, Qt::IgnoreAspectRatio);//保持高度拉宽
    pix_4 = pix_4.scaled(iHorzSplit, DstHeight-iVertSplit*2, Qt::IgnoreAspectRatio);//保持宽度拉高
    pix_5 = pix_5.scaled(DstWidth-iHorzSplit*2,DstHeight-iVertSplit*2, Qt::IgnoreAspectRatio);//宽高都缩放
    pix_6 = pix_6.scaled(iHorzSplit, DstHeight-iVertSplit*2, Qt::IgnoreAspectRatio);//保持宽度拉高
    pix_8 = pix_8.scaled(DstWidth-iHorzSplit*2, iVertSplit);//保持高度拉宽
 
 
    QPixmap* resultImg =new QPixmap(DstWidth, DstHeight);
    QPainter* painter = new QPainter(resultImg);
    if (!resultImg->isNull()) {
        painter->drawPixmap(0,0,pix_1);
        painter->drawPixmap(iHorzSplit, 0, pix_2);
        painter->drawPixmap(DstWidth-iHorzSplit,0,pix_3);
 
        painter->drawPixmap(0, iVertSplit, pix_4);
        painter->drawPixmap(iHorzSplit, iVertSplit, pix_5);
        painter->drawPixmap(DstWidth-iHorzSplit, iVertSplit, pix_6);
 
        painter->drawPixmap(0, DstHeight-iVertSplit, pix_7);
        painter->drawPixmap(iHorzSplit, DstHeight-iVertSplit, pix_8);
        painter->drawPixmap(DstWidth-iHorzSplit, DstHeight-iVertSplit, pix_9);
        painter->end();
    }
    return resultImg;
}


参考链接:http://bbs.csdn.net/topics/390506636




你可能感兴趣的:(Qt)