Qt中QPainter提供了繪制圖像的API,極大地方便了我們對圖像的繪制。
Qt中提供了QPixmap, QBitmap,QBitMapQImage,QPicture等圖像繪圖設備,它們的類關系如下圖所示:
QPixmap繼承了QPaintDevice,您可用以建立QPainter並於上進行繪圖,您也可以直接指定圖案加載Qt所支持的圖檔,像是BMP、GIF、JPG、JPEG、PNG等,並使用QPainter的drawPixmap()繪制在其它的繪圖裝置上。您可以在QLabel、QPushButton上設定QPixmap以顯示圖像。QPixmap是針對屏幕顯示圖像而設計並最佳化,依賴於所在平台的原生繪圖引擎,所以一些效果的展現(像是反鋸齒),在不同的平台上可能會有不一致的結果。
QBitmap是QPixmap的子類別,提供單色圖像,可用於制作光標(QCursor)或筆刷(QBrush)物件。
QPixmap使用平台的繪圖引擎,在不同的平台所呈現的效果不一,無法提供個別像素的存取,QImage使用Qt自身的繪圖引擎,可提供在不同平台上相同的圖像呈現效果,並可透過setPixpel()、pixel()等方法,直接存取指定的像素。
QPicture則是個繪圖裝置,可以記錄並回放QPainter的繪圖指令,您可以使用QPainter的begin()方法,指定在QPicture上進行繪圖,使用end()方法結束繪圖,使用QPicture的save()方法將QPainter所使用過的繪圖指令存至檔案
QPainter繪圖引擎提供了drawImage、drawPicture和drawPixmap三類重載API。
drawImage類API支持繪制正常大小和自適應大小兩種圖片顯示模式;
drawPicture類API支持繪制正常大小圖片顯示模式,主要用於回放QPainter的繪制;
drawPixmap類API支持繪制正常大小和自適應大小兩種圖片顯示模式;
drawTiledPixmap提供了平鋪顯示模式。
綜上,使用QPixmap結合QPainter可以繪制正常大小、自適應大小和平鋪三種模式。
1、在指定位置繪制 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)
2、指定的矩形內繪制 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)
3、繪制 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)
4、平鋪繪制 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)
測試代碼:
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); |