C++ (Qt)#ifndef SCALEDIMAGE_H#define SCALEDIMAGE_H #include <QWidget>#include <QPainter>#include <QPaintEvent> class ScaledImage : public QWidget { Q_OBJECTpublic: ScaledImage(QWidget *parent = 0) : QWidget(parent), mKeepAspectRatio(true) {} protected: void paintEvent(QPaintEvent *e) { if (!mPixmap.isNull()) { QPainter p(this); if (mKeepAspectRatio){ QPointF delta(e->rect().width() / (double)mPixmap.size().width(), e->rect().height() / (double)mPixmap.size().height()); QSize size; if (delta.x() < delta.y()) { size.setWidth(delta.x() * mPixmap.size().width()); size.setHeight(delta.x() * mPixmap.size().height()); } else { size.setWidth(delta.y() * mPixmap.size().width()); size.setHeight(delta.y() * mPixmap.size().height()); } QPoint topLeft((e->rect().size().width() - size.width()) / 2, (e->rect().size().height() - size.height()) / 2); p.drawPixmap(QRect(topLeft, size), mPixmap, mPixmap.rect()); } else { p.drawPixmap(e->rect(), mPixmap, mPixmap.rect()); } } } public slots: void setPixmap(const QPixmap &pixmap) { mPixmap = pixmap; update(); } void setKeepAspectRatio(const bool value) { mKeepAspectRatio = value; } bool keepAspectRatio() const { return mKeepAspectRatio; } private: QPixmap mPixmap; bool mKeepAspectRatio;}; #endif // SCALEDIMAGE_H
C++ (Qt)while(!asleep()) sheep++;
C++ (Qt)void paintEvent(QPaintEvent *e) { if (!mPixmap.isNull()) { QPainter p(this); p.drawPixmap(e->rect(), mPixmap, mPixmap.rect()); }}