一个在Ubuntu平台的opengl的例子

294 阅读1分钟

OpenGL有很强的渲染效果.我们可以把QML界面和OpenGL结合起来得到更强的渲染效果.在今天的例子中,我们仿照例程"Scene Graph - OpenGL Under QML",并把它移植到我们的Ubuntu手机平台中来.

\

为了移植的方便,我们采用了我们Ubuntu SDK中的"QtQuick App with QML UI (qmake)"模版.

\

\

\

这个模版的好处是可以很容把我们所需要的C++代码加入到我们的应用中去.我们需要把我们的C++代码加入到我们的.pro文件中:

\

SOURCES += main.cpp squircle.cpp
HEADERS += squircle.h


另外:

main.cpp

\

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickView>

#include "squircle.h"

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    qmlRegisterType<Squircle>("OpenGLUnderQML", 1, 0, "Squircle");

    QQuickView view;
    view.setSource(QUrl(QStringLiteral("qrc:///Main.qml")));
    view.setResizeMode(QQuickView::SizeRootObjectToView);
    view.show();
    return app.exec();
}

\

这里,我们把"Squircle"进行注册,并在我们的QML文件中可以实例化.

\

\

Main.qml

\

import QtQuick 2.0
import Ubuntu.Components 1.1

import OpenGLUnderQML 1.0

Item {
    width: 320
    height: 480

    Squircle {
        SequentialAnimation on t {
            NumberAnimation { to: 1; duration: 2500; easing.type: Easing.InQuad }
            NumberAnimation { to: 0; duration: 2500; easing.type: Easing.OutQuad }
            loops: Animation.Infinite
            running: true
        }
    }

    //! [1] //! [2]
    Rectangle {
        color: Qt.rgba(1, 1, 1, 0.7)
        radius: 10
        border.width: 1
        border.color: "white"
        anchors.fill: label
        anchors.margins: -10
    }

    Text {
        id: label
        color: "black"
        wrapMode: Text.WordWrap
        text: "The background here is a squircle rendered with raw OpenGL using the 'beforeRender()' signal in QQuickWindow. This text label and its border is rendered using QML"
        anchors.right: parent.right
        anchors.left: parent.left
        anchors.bottom: parent.bottom
        anchors.margins: 20
    }
}


注意,我们不能再使用MainView及Page了,否则我们不能正确地显示我们的画面.

\

运行我们的应用:

\

\

\

\

从上面我们可以看出来,OpenGL可以和QML完美地结合在一起.

\

整个项目的源码在:github.com/liu-xiao-gu…