TouchGFX之自定义控件

在创建应用时,您可能需要TouchGFX中没有包含的控件。在创建应用时,您可能需要TouchGFX中没有包含的控件。但有时此法并不够用,当您需要全面控制帧缓冲时,您需要使用自定义控件法。

TouchGFX Designer目前不支持自定义控件的创建。 因此,您将需要手动写入自定义控件的代码,然后在视图的用户代码部分插入控件。

示例为自定义一个二维码控件

#ifndef QR_CODE_HPP
#define QR_CODE_HPP
#include <touchgfx/hal/Types.hpp>

class QRCode
{
public:
    /* 获取该坐标值 */
    bool at(uint16_t x, uint16_t y) const;

    /* 获取宽度 */
    uint16_t getWidth() const;

    /* 获取高度 */
    uint16_t getHeight() const;
};

#endif
#include <gui/model/QRCode.hpp>
#include <stdlib.h>

bool QRCode::at(uint16_t x, uint16_t y) const
{
    srand(x*123456+y*getWidth()*23456789);
    for(int i = 0; i < 100; i++)
    {
        srand(rand());
    }
    return ((rand() / (float)RAND_MAX) > 0.5f);
}

uint16_t QRCode::getWidth() const
{
    return 16;
}

uint16_t QRCode::getHeight() const
{
    return 16;
}
#ifndef QR_CODE_WIDGET_HPP
#define QR_CODE_WIDGET_HPP
#include <touchgfx/widgets/Widget.hpp>
#include <gui/model/QRCode.hpp>
#include <touchgfx/hal/Types.hpp>

class QRCodeWidget : public touchgfx::Widget
{
public:
    QRCodeWidget();

    /* 绘制 */
    virtual void draw(const touchgfx::Rect& invalidatedArea) const;

    /* 获取实心区域 */
    virtual touchgfx::Rect getSolidRect() const;

    /* 设置二维码成员变量 */
    void setQRCode(QRCode *code);

    /* 设置缩放比例成员变量 */
    void setScale(uint8_t s);

private:
		/* 更新二维码控件尺寸 */
    void updateSize();

    QRCode *code;
    uint8_t scale;
};

#endif
#include <gui/common/QRCodeWidget.hpp>
#include <touchgfx/hal/HAL.hpp>

QRCodeWidget::QRCodeWidget() : 
    code(0),
    scale(1)
{
}

void QRCodeWidget::setQRCode(QRCode *qrCode)
{
    code = qrCode;
    updateSize();
}

void QRCodeWidget::draw(const touchgfx::Rect& invalidatedArea) const
{
    if(!code)
    {
        return;
    }

    touchgfx::Rect absolute = getAbsoluteRect();

    uint16_t *framebuffer = touchgfx::HAL::getInstance()->lockFrameBuffer();

    for(int y = invalidatedArea.y; y < invalidatedArea.bottom(); y++)
    {
        for(int x = invalidatedArea.x; x < invalidatedArea.right(); x++)
        {
            framebuffer[absolute.x + x + (absolute.y + y) * touchgfx::HAL::DISPLAY_WIDTH] = code->at(x / scale, y / scale) ? 0x0000 : 0xffff;
        }
    }

    touchgfx::HAL::getInstance()->unlockFrameBuffer();
}

touchgfx::Rect QRCodeWidget::getSolidRect() const
{
    return touchgfx::Rect(0,0,getWidth(), getHeight());
}

void QRCodeWidget::setScale(uint8_t s)
{
    scale = s;
    updateSize();
}

void QRCodeWidget::updateSize()
{
    if(code)
    {
        setWidth(code->getWidth() * scale);
        setHeight(code->getHeight() * scale);
    }    
}
#include <gui/screen_screen/screenView.hpp>

screenView::screenView()
{

}

void screenView::setupScreen()
{
    screenViewBase::setupScreen();
		myQRCodeWidget.setScale(10);
		myQRCodeWidget.setQRCode(&myQRCode);
		add(myQRCodeWidget);
}

void screenView::tearDownScreen()
{
    screenViewBase::tearDownScreen();
}

运行模拟器:显示效果如下

猜你喜欢

转载自blog.csdn.net/lushoumin/article/details/133095179