帮我写一个qt调用opengl实时绘制图片滚动的程序
时间: 2023-05-29 20:02:08 浏览: 162
这是一个使用Qt和OpenGL绘制滚动图片的程序。它使用QOpenGLWidget类来创建一个OpenGL上下文,然后使用OpenGL函数来绘制图像,并在每个帧之间使用QTimer类来更新图像的位置。
#include <QtWidgets/QApplication>
#include <QtWidgets/QOpenGLWidget>
#include <QtCore/QTimer>
#include <QtGui/QImage>
#include <QtGui/QPainter>
class ScrollImage : public QOpenGLWidget {
public:
ScrollImage(QWidget* parent = nullptr)
: QOpenGLWidget(parent)
{
QTimer* timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &ScrollImage::updatePosition);
timer->start(16);
}
void setImage(const QImage& image)
{
m_image = image;
update();
}
protected:
void initializeGL() override
{
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glEnable(GL_TEXTURE_2D);
glGenTextures(1, &m_textureId);
glBindTexture(GL_TEXTURE_2D, m_textureId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
}
void paintGL() override
{
glClear(GL_COLOR_BUFFER_BIT);
if (!m_image.isNull()) {
QImage image = m_image.mirrored(false, true); // Flip the image vertically
glBindTexture(GL_TEXTURE_2D, m_textureId);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width(), image.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, image.bits());
glBegin(GL_QUADS);
glTexCoord2f(0.0f, m_position);
glVertex2f(-1.0f, 1.0f);
glTexCoord2f(1.0f, m_position);
glVertex2f(1.0f, 1.0f);
glTexCoord2f(1.0f, m_position - 1.0f);
glVertex2f(1.0f, -1.0f);
glTexCoord2f(0.0f, m_position - 1.0f);
glVertex2f(-1.0f, -1.0f);
glEnd();
}
}
void resizeGL(int width, int height) override
{
glViewport(0, 0, width, height);
}
private:
void updatePosition()
{
m_position += 0.02f;
if (m_position > 1.0f) {
m_position = 0.0f;
}
update();
}
QImage m_image;
GLuint m_textureId = 0;
float m_position = 0.0f;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QImage image(":/image.jpg");
if (image.isNull()) {
qCritical() << "Failed to load image";
return -1;
}
ScrollImage w;
w.setGeometry(100, 100, image.width(), image.height());
w.setWindowTitle("Scroll Image");
w.setImage(image);
w.show();
return a.exec();
}
要运行此程序,您需要将一张名为“image.jpg”的图像添加到您的项目中,并将其路径添加到QImage构造函数中。运行程序后,您将看到图像从上到下滚动。每秒大约更新60次,因为定时器更新率为每16毫秒一次。您可以通过调整计时器时间来更改更新率。
阅读全文