QPainter繪製圖片填充方式(正常大小、剪切大小、自適應大小、平鋪)

Qt中QPainter提供了繪製圖像的API,極大地方便了咱們對圖像的繪製。測試

Qt中提供了QPixmap, QBitmap,QBitMapQImage,QPicture等圖像繪圖設備,它們的類關係以下圖所示:spa

QPixmap繼承了QPaintDevice,您可用以創建QPainter並於上進行繪圖,您也能夠直接指定圖案加載Qt所支持的圖檔,像是BMP、GIF、JPG、JPEG、PNG等,並使用QPainter的drawPixmap()繪製在其它的繪圖裝置上。您能夠在QLabel、QPushButton上設定QPixmap以顯示圖像。QPixmap是針對屏幕顯示圖像而設計並最佳化,依賴於所在平臺的原生繪圖引擎,因此一些效果的展示(像是反鋸齒),在不一樣的平臺上可能會有不一致的結果。設計

QBitmap是QPixmap的子類別,提供單色圖像,可用於製做光標(QCursor)或筆刷(QBrush)物件。blog

QPixmap使用平臺的繪圖引擎,在不一樣的平臺所呈現的效果不一,沒法提供個別像素的存取,QImage使用Qt自身的繪圖引擎,可提供在不一樣平臺上相同的圖像呈現效果,並可透過setPixpel()、pixel()等方法,直接存取指定的像素。繼承

QPicture則是個繪圖裝置,能夠記錄並回放QPainter的繪圖指令,您能夠使用QPainter的begin()方法,指定在QPicture上進行繪圖,使用end()方法結束繪圖,使用QPicture的save()方法將QPainter所使用過的繪圖指令存至檔案圖片

 

QPainter繪圖引擎提供了drawImage、drawPicture和drawPixmap三類重載API。ip

drawImage類API支持繪製正常大小和自適應大小兩種圖片顯示模式;ci

drawPicture類API支持繪製正常大小圖片顯示模式,主要用於回放QPainter的繪製;get

drawPixmap類API支持繪製正常大小和自適應大小兩種圖片顯示模式;qt

drawTiledPixmap提供了平鋪顯示模式。

綜上,使用QPixmap結合QPainter能夠繪製正常大小、自適應大小和平鋪三種模式。

 

一、在指定位置繪製 pixmap,pixmap 不會被縮放

/* pixmap 的左上角和 widget 上 x, y 處重合 */

void QPainter::drawPixmap(int x, int y, const QPixmap & pixmap)

void QPainter::drawPixmap(const QPointF &point, const QPixmap &pixmap)

二、指定的矩形內繪製 pixmap,pixmap 被縮放填充到此矩形內

/* target 是 widget 上要繪製 pixmap 的矩形區域 */

void QPainter::drawPixmap(int x, int y, int width, int height, const QPixmap &pixmap)

void QPainter::drawPixmap(const QRect &target, const QPixmap &pixmap)

三、繪製 pixmap 的一部分,能夠稱其爲 sub-pixmap(剪切大小)

/* source 是 sub-pixmap 的 rectangle */

void QPainter::drawPixmap(const QPoint &point, const QPixmap &pixmap, const QRect &source)

void QPainter::drawPixmap(const QRect &target, const QPixmap &pixmap, const QRect &source)

void QPainter::drawPixmap(int x, int y, const QPixmap &pixmap, int sx, int sy, int sw, int sh)

四、平鋪繪製 pixmap,水平和垂直方向都會同時使用平鋪的方式

void QPainter::drawTiledPixmap(const QRect &rectangle, const QPixmap &pixmap, const QPoint &position = QPoint())

void QPainter::drawTiledPixmap(int x, int y, int width, int height, const QPixmap & pixmap, int sx = 0, int sy = 0)

 

測試代碼:

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
painter->setRenderHint(QPainter::Antialiasing);
QRectF target(-m_size /  2 , -m_size /  2 , m_size, m_size);
QRectF source(
0 . 0 0 . 0 128 . 0 128 . 0 );
QRectF clipSource(
0 . 0 0 . 0 100 . 0 100 . 0 );
QPixmap pixmap(
":/image/qt-rocket.png" );
// 自適應
painter->drawImage(target, image, source);
// 正常大小
painter->drawImage(QPointF(-m_size /  2 , -m_size /  2 ), image, source);
// 子大小
painter->drawImage(QPointF(-m_size /  2 , -m_size /  2 ), image, clipSource);
// 平鋪
painter->drawTiledPixmap(target, pixmap);

相關文章
相關標籤/搜索