UtiLite
0.3.1
A lite utilities library
|
00001 /* 00002 * ImageView.h 00003 * 00004 * Created on: 2012-06-20 00005 * Author: mathieu 00006 */ 00007 00008 #ifndef IMAGEVIEW_H_ 00009 #define IMAGEVIEW_H_ 00010 00011 #include "utilite/UtiLiteQtExp.h" // DLL export/import defines 00012 00013 00014 #include <QtGui/QWidget> 00015 #include <QtGui/QPainter> 00016 00024 class UTILITEQT_EXP UImageView : public QWidget 00025 { 00026 Q_OBJECT; 00027 public: 00028 UImageView(QWidget * parent = 0) : QWidget(parent) {} 00029 ~UImageView() {} 00030 void setBackgroundBrush(const QBrush & brush) {brush_ = brush;} 00031 00032 public slots: 00033 void setImage(const QImage & image) 00034 { 00035 if(pixmap_.width() != image.width() || pixmap_.height() != image.height()) 00036 { 00037 this->setMinimumSize(image.width(), image.height()); 00038 this->setGeometry(this->geometry().x(), this->geometry().y(), image.width(), image.height()); 00039 } 00040 pixmap_ = QPixmap::fromImage(image); 00041 this->update(); 00042 } 00043 00044 private: 00045 void computeScaleOffsets(float & scale, float & offsetX, float & offsetY) 00046 { 00047 scale = 1.0f; 00048 offsetX = 0.0f; 00049 offsetY = 0.0f; 00050 00051 if(!pixmap_.isNull()) 00052 { 00053 float w = pixmap_.width(); 00054 float h = pixmap_.height(); 00055 float widthRatio = float(this->rect().width()) / w; 00056 float heightRatio = float(this->rect().height()) / h; 00057 00058 if(widthRatio < heightRatio) 00059 { 00060 scale = widthRatio; 00061 } 00062 else 00063 { 00064 scale = heightRatio; 00065 } 00066 00067 w *= scale; 00068 h *= scale; 00069 00070 if(w < this->rect().width()) 00071 { 00072 offsetX = (this->rect().width() - w)/2.0f; 00073 } 00074 if(h < this->rect().height()) 00075 { 00076 offsetY = (this->rect().height() - h)/2.0f; 00077 } 00078 } 00079 } 00080 00081 protected: 00082 virtual void paintEvent(QPaintEvent *event) 00083 { 00084 QPainter painter(this); 00085 00086 //Draw background 00087 painter.save(); 00088 painter.setBrush(brush_); 00089 painter.drawRect(this->rect()); 00090 painter.restore(); 00091 00092 if(!pixmap_.isNull()) 00093 { 00094 painter.save(); 00095 //Scale 00096 float ratio, offsetX, offsetY; 00097 this->computeScaleOffsets(ratio, offsetX, offsetY); 00098 painter.translate(offsetX, offsetY); 00099 painter.scale(ratio, ratio); 00100 painter.drawPixmap(QPoint(0,0), pixmap_); 00101 painter.restore(); 00102 } 00103 } 00104 00105 private: 00106 QPixmap pixmap_; 00107 QBrush brush_; 00108 }; 00109 00110 00111 #endif /* IMAGEVIEW_H_ */