Как создать гистограмму с помощью собственного метода Blackberry 10

Я пытаюсь создать гистограмму, используя данные JSON, которые я получаю от веб-сервисов, в основном мое требование - показать «Гистограмму», используя данные «JSON».

По сути, я Android-разработчик и новичок в Blackberry 10 Native, поэтому я мало что знаю о Blackberry, поэтому, если кто-нибудь может помочь мне в создании графика в Blackberry-10.

Я много искал в Google и везде, где только можно, но не пришел ни к какому выводу. Тем не менее я ищу решение для этого, поэтому в основном мои данные «JSON» имеют следующий формат.

{"Ax":"3:41","Ay":"04:41","Bx":"10:47 ","By":"12:47","Cx":"18:30","Cy":"19:30","Az":3,"Bz":2,"Cz":1,"condition":2}

Здесь "Ax":"3:41","Ay":"04:41" это параметр - это час начала и окончания работы, и, наконец, он вычисляет общее количество часов, например "Az":3,"Bz":2,"Cz":1, и генерирует график на основе этого. Точно так же мой график будет выглядеть примерно так

http://postimg.org/image/nb6dnpwax/

Пожалуйста, помогите мне, как я могу создать график на основе этого, некоторые ссылки, на которые я ссылался для создания графика,

http://elycharts.com/examples
http://g.raphaeljs.com/
Как создавать диаграммы/графики (такие как линейные графики, гистограммы, круговые диаграммы) и т. д. в C++, Qt, QML, Blackberry 10 Cascades Beta 3 SDK?
http://devblog.blackberry.com/2014/01/conference-app-secrets-part-3-json-vs-xml/

Одна вещь, которую я четко упомянул, это то, что мне нужно решение с использованием qml и C++ с Blackberry-10, поэтому, пожалуйста, не предлагайте никаких других методов, таких как Java и все такое.

Заранее благодарю вас за помощь.


person user3660803    schedule 10.07.2014    source источник
comment
Насколько мне известно, графических библиотек для bb10 пока нет. Вероятно, проще всего было бы построить собственный граф с использованием контейнеров. Внезапно я бы порекомендовал установить основной контейнер для абсолютного макета, а затем позиционировать контейнеры для каждого бара внутри него.   -  person hyarion    schedule 10.07.2014
comment
У меня есть для вас решение, которое я опубликую, когда вернусь домой и получу доступ к своей кодовой базе. Взгляните на снимки экрана для этого приложения: appworld.blackberry. com/webstore/content/128442/ Третий показывает гистограммы. Техника в основном рисует QImage, который имеет довольно хороший пакет рисования, а затем передает Cascades ImageView.   -  person Richard    schedule 10.07.2014
comment
@Hyarion, спасибо за ваше предложение, я тоже попробую ваше решение и свяжусь с вами, когда закончу свою задачу.   -  person user3660803    schedule 11.07.2014


Ответы (1)


Итак, есть эта статья на Форумы поддержки BlackBerry. Здесь есть все основы, но я так много работаю с изображениями, сгенерированными во время выполнения, что решил создать класс для их инкапсуляции. По запросу здесь представлен простой образец, основанный на одном из шаблонов Cascades. Вам также следует ознакомиться с документацией по адресу:

И образцы файлов в BlackBerry GIT Hub.

QML-файл:

/*
 * Copyright (c) 2011-2014 BlackBerry Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import bb.cascades 1.2

Page {
    Container {
        layout: DockLayout {

        }
        Label {
            // Localized text with the dynamic translation and locale updates support
            text: qsTr("Bar Graph") + Retranslate.onLocaleOrLanguageChanged
            textStyle.base: SystemDefaults.TextStyles.BigText
            horizontalAlignment: HorizontalAlignment.Center
        }
        ImageView {
            objectName: "barGraph"
            verticalAlignment: VerticalAlignment.Center
            horizontalAlignment: HorizontalAlignment.Center
        }
    }
}

Вот заголовочный файл:

 /*
 * DrawableImage.hpp
 *
 *  Created on: Jul 11, 2014
 *      Author: richard
 */

#ifndef DRAWABLEIMAGE_HPP_
#define DRAWABLEIMAGE_HPP_

#include <bb/ImageData>
#include <QtGui/QImage>
#include <bb/cascades/ImageView>

namespace net
{
    namespace test
    {

        class DrawableImage : public QImage
        {
        public:
            DrawableImage();
            DrawableImage(QSize imageSize, QImage::Format format);
            virtual ~DrawableImage();

            void    emitRenderingBegin();
            void    emitRenderingFinished();

            DrawableImage&  operator = (const QImage &image) { QImage::operator =(image); return *this; }

            QPainter        &painter();

        public:
            void    updateToView(bb::cascades::ImageView *imageView);

        private:
                void    deleteBuffer();

                QPainter        m_painter;
                QSize           m_sizeInPixels;
                unsigned char*  m_buffer; // pixel data in PixelBufferData format
        };

    } /* namespace test */
} /* namespace net */

#endif /* DRAWABLEIMAGE_HPP_ */

И файл cpp:

/*
 * DrawableImage.cpp
 *
 *  Created on: Jul 11, 2014
 *      Author: richard
 */

#include <src/DrawableImage.hpp>

namespace net
{
    namespace test
    {

        DrawableImage::DrawableImage()
            : m_painter(), m_sizeInPixels(0,0), m_buffer(NULL)
        {
            // TODO Auto-generated constructor stub

        }

        DrawableImage::DrawableImage(QSize imageSize, QImage::Format format)
            : QImage(imageSize, format), m_painter(), m_sizeInPixels(0,0), m_buffer(NULL)
        {

        }


        DrawableImage::~DrawableImage() {
            // TODO Auto-generated destructor stub
        }

        /*
        void DrawableImage::emitRenderingBegin() {
            emit renderingBegin();
        }

        void DrawableImage::emitRenderingFinished() {
            emit renderingFinished();
        }
        */

        QPainter& DrawableImage::painter() {
            if (!m_painter.isActive()) {
                m_painter.begin(this);
            }

            return m_painter;
        }

        void DrawableImage::deleteBuffer()
        {
            if (m_buffer != 0)
            {
                delete [] m_buffer;
                m_buffer = 0;
            }
        }

        void    DrawableImage::updateToView(bb::cascades::ImageView *imageView) {
            if (m_painter.isActive()) {
                m_painter.end();
            }

            Q_ASSERT(imageView != NULL);

            QImage swapped     = rgbSwapped();
            QSize  swappedSize = swapped.size();

            int w = swappedSize.width();
            int h = swappedSize.height();

            int numBytes  = w * h * 4;
            if (swappedSize != m_sizeInPixels)
            {
                deleteBuffer();
                m_sizeInPixels = QSize(w, h);
                m_buffer = new uchar[numBytes];
            }

            // Copy the memory over.
            // We'll add defensive code in case rgbSwapped has a different size
            const uchar* from = swapped.constBits();
            int numFromBytes = swapped.numBytes();
            int numToCopy = std::min(numFromBytes, numBytes);

            memcpy(m_buffer, from, numToCopy);
            if (numToCopy < numBytes)
            {
                memset(m_buffer + numToCopy, 0x00, numBytes - numToCopy);
            }

            bb::ImageData imageData = bb::ImageData::fromPixels(m_buffer, bb::PixelFormat::RGBA_Premultiplied,
                                   m_sizeInPixels.width(),
                                   m_sizeInPixels.height(),
                                   m_sizeInPixels.width() * 4);

            imageView->setImage(imageData);
        }


    } /* namespace test */
} /* namespace net */

А вот и applicationui.cpp (applicationui.hpp не изменен):

/*
 * Copyright (c) 2011-2014 BlackBerry Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "applicationui.hpp"

#include <bb/cascades/Application>
#include <bb/cascades/QmlDocument>
#include <bb/cascades/AbstractPane>
#include <bb/cascades/LocaleHandler>

#include <src/DrawableImage.hpp>

using namespace bb::cascades;
using namespace net::test;

ApplicationUI::ApplicationUI() :
        QObject()
{
    // prepare the localization
    m_pTranslator = new QTranslator(this);
    m_pLocaleHandler = new LocaleHandler(this);

    bool res = QObject::connect(m_pLocaleHandler, SIGNAL(systemLanguageChanged()), this, SLOT(onSystemLanguageChanged()));
    // This is only available in Debug builds
    Q_ASSERT(res);
    // Since the variable is not used in the app, this is added to avoid a
    // compiler warning
    Q_UNUSED(res);

    // initial load
    onSystemLanguageChanged();

    // Create scene document from main.qml asset, the parent is set
    // to ensure the document gets destroyed properly at shut down.
    QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(this);

    // Create root object for the UI
    AbstractPane *root = qml->createRootObject<AbstractPane>();

    /*
     * This code exercises the DrawableImage
     */
    QSize   graphImageSize(700, 700);
    DrawableImage    graph;
    ImageView* graphImageView = root->findChild<ImageView*>("barGraph");

    // Initialise graph and fill with transparent black.
        graph = QImage(graphImageSize, QImage::Format_ARGB32_Premultiplied);
        graph.fill(Qt::black);

        // Set the background mode
        graph.painter().setBackgroundMode(Qt::TransparentMode);

        // Set rendering hints
        graph.painter().setRenderHint(QPainter::Antialiasing, true);

        for (int i = 0; i < 10; i++) {

            int x = i * (graphImageSize.width()/10);
            int h = i * (graphImageSize.height()/10) + graphImageSize.height()/20;
            int w = graphImageSize.width()/10 - 20;

            graph.painter().fillRect( x + 10, graphImageSize.height()-h, w, h, Qt::darkGreen);
        }

    // Once the image is drawn transfer it to the Cascades ImageView
    graph.updateToView(graphImageView);

    // Set created root object as the application scene
    Application::instance()->setScene(root);
}

void ApplicationUI::onSystemLanguageChanged()
{
    QCoreApplication::instance()->removeTranslator(m_pTranslator);
    // Initiate, load and install the application translation files.
    QString locale_string = QLocale().name();
    QString file_name = QString("BarGraph_%1").arg(locale_string);
    if (m_pTranslator->load(file_name, "app/native/qm")) {
        QCoreApplication::instance()->installTranslator(m_pTranslator);
    }
}

Вам также нужно будет добавить строку LIBS в файл .pro:

APP_NAME = BarGraph

CONFIG += qt warn_on cascades10
LIBS += -lbb

include(config.pri)

Вот результат:

введите здесь описание изображения

person Richard    schedule 10.07.2014
comment
Привет, Ричард, спасибо за ваш ответ, позвольте мне реализовать это в моем коде, и я свяжусь с вами, но спасибо за ваш быстрый ответ. Благодаря тонну... - person user3660803; 11.07.2014
comment
Привет, Ричард. Не могли бы вы рассказать мне, как я могу реализовать этот полный пример. Или же вы можете предоставить полный пример с qml и всем C++, так как я очень новичок в Blackberry-10, я не знаю, как я могу реализовать этот пример. Спасибо за поддержку. - person user3660803; 11.07.2014
comment
Я не знаю, насколько конкретным я могу быть, не зная вашего варианта использования, но это должно вас заинтересовать. - person Richard; 11.07.2014
comment
Привет, Ричард, у меня не хватает слов, чтобы поблагодарить тебя, ты классный человек, действительно здорово помог. Благодаря тонну. Вы гениальный человек. - person user3660803; 12.07.2014
comment
Просто напишите отличные нативные приложения BB10 ;) - person Richard; 12.07.2014