本页内容

C

实现矢量图形支持

本主题说明了如果目标平台支持硬件加速矢量图形,应如何实现该功能。

概述

矢量路径

一个矢量图形示例,展示了系列路径命令。

矢量路径通常表示为一系列路径命令。例如,前一张图片中的路径可以定义为一个 SVG 路径:

M 21,26.50 V 60 H 69 C 69,60 21,60 21,26.50 Z

其中 M:MoveTo(移动到)、V:LineTo(垂直线段)、H:LineTo(水平线段)、C:三次贝塞尔曲线、Z:ClosePath(闭合路径)是路径命令。数值代表每个命令的坐标。由于这些命令以大写字母表示,因此其参数被视为绝对坐标。

矢量路径的表示形式

在平台接口中,矢量路径由PlatformInterface::PathData 类表示。对于前面的示例路径,输出结果如下:

函数输出
PathData::segmentCount()5
PathData::segments()
Qul::PlatformInterface::PathData::SegmentType [5] {
    MoveSegment, LineSegment, LineSegment, CubicBezierSegment, CloseSegment
}
PathData::controlElementCount()12
PathData::controlElements()示例路径的值存储为:
float [12] { x1, y1, x2, y2, x3, y3, cx1, cy1, cx2, cy2, x4, y4 }

坐标如下:

float [12] { 21.0f, 26.5f, 21.0f, 60.0f, 69.0f, 60.0f, 69.0f, 60.0f, 21.0f, 60.0f, 21.0f, 26.5f }

注意:垂直线和水平线均以 包含 x 和 y 坐标的 LineSegments 形式存储。

图形驱动程序路径示例

示例图形驱动程序接口使用int32_t 作为路径命令和参数,以表示矢量路径。它采用S16.15定点格式表示坐标,且每个矢量路径均以END 命令结尾。路径命令是预定义的整数值。前一个示例中使用的矢量路径可表示为:

int32_t [] { MOVETO, x1, y1, LINETO, x2, y2, LINETO, x3, y3, CUBIC, cx1, cy1, cx2, cy2, x4, y4, CLOSE, END }

坐标转换为 S16.15 格式:

int32_t [] { MOVETO, 21.0*(1<<15), 26.5*(1<<15), LINETO, 21.0*(1<<15), 60.0*(1<<15), LINETO, ... }

实现矢量图形支持

绘图引擎的重写

要实现对矢量图形的支持,请继承PlatformInterface::DrawingEngine 类并重写以下函数:

class ExampleDrawingEngine : public PlatformInterface::DrawingEngine
{
public:
    ...
    PlatformInterface::DrawingEngine::Path *allocatePath(const PlatformInterface::PathData *pathData,
                                                         PlatformInterface::PathFillRule fillRule) QUL_DECL_OVERRIDE;

    void setStrokeProperties(PlatformInterface::DrawingEngine::Path *path,
                             const PlatformInterface::StrokeProperties &strokeProperties) QUL_DECL_OVERRIDE;

    void blendPath(PlatformInterface::DrawingDevice *drawingDevice,
                   PlatformInterface::DrawingEngine::Path *path,
                   const PlatformInterface::Transform &transform,
                   const PlatformInterface::Rect &clipRect,
                   const PlatformInterface::Brush *fillBrush,
                   const PlatformInterface::Brush *strokeBrush,
                   int sourceOpacity,
                   PlatformInterface::DrawingEngine::BlendMode blendMode) QUL_DECL_OVERRIDE;

    PlatformInterface::RenderHints supportedRenderHints() const QUL_DECL_OVERRIDE;
};

路径预处理

接下来,创建PlatformInterface::DrawingEngine::Path 的子类,用于存储特定于平台的路径数据。该ExamplePath 采用与前面所述示例图形驱动程序相同的格式。

struct ExamplePath : public PlatformInterface::DrawingEngine::Path
{
    // S16.15 fixed point factor
    static const int32_t fixedPointFactor = (1 << 15);

    int16_t fillRule;

    ExamplePath(const PlatformInterface::PathData *pathData, PlatformInterface::PathFillRule fillRule);

    void free() { PlatformInterface::qul_delete(this); }

    const PlatformInterface::PathData *getPathData() { return path; }

    // Functions to access stored path/stroke elements
    int32_t *getFillPathData(void) { return fillElements.data(); }
    int32_t *getStrokePathData(void) { return strokeElements.data(); }

    // Functions to store fill elements in the platform optimized format
    inline void addElement(int32_t element) { fillElements.push_back(element); }
    inline void addElement(float element)
    {
        // Convert floating point values to fixed point
        fillElements.push_back(static_cast<int32_t>(element * fixedPointFactor));
    }

    // Functions to store stroke elements in the platform optimized format
    inline void addStrokeElement(int32_t element) { strokeElements.push_back(element); }
    inline void addStrokeElement(float element)
    {
        // Convert floating point values to fixed point
        strokeElements.push_back(static_cast<int32_t>(element * fixedPointFactor));
    }

    // Function to convert fill path data to platform optimized format
    void processFillPath();

    // Functions to return current element counts
    int32_t fillPathSize() { return fillElements.size() * sizeof(int32_t); }
    int32_t strokePathSize() { return strokeElements.size() * sizeof(int32_t); }

    // Functions to remove fill/stroke elements
    void clearStroke() { strokeElements.clear(); }
    void clearFill() { fillElements.clear(); }

private:
    // Status flag of the vector path preprocessing
    bool processingDone;

    // Path data in the common format
    const PlatformInterface::PathData *path;

    // Fill/stroke data format optimized for the platform
    std::vector<int32_t, Qul::PlatformInterface::Allocator<int32_t> > fillElements;
    std::vector<int32_t, Qul::PlatformInterface::Allocator<int32_t> > strokeElements;
};

fillRule 可以在结构体构造函数中转换为特定于平台的格式。

ExamplePath::ExamplePath(const PlatformInterface::PathData *pathData, PlatformInterface::PathFillRule fillRule)
    : fillRule(fillRule == PlatformInterface::PathWindingFill ? HW_PATH_FILL_NON_ZERO : HW_PATH_FILL_FILL_EVEN_ODD)
    , processingDone(false)
    , path(pathData)
{}

接下来,编写一个函数,利用PlatformInterface::PathDataIterator 遍历路径数据,并将其转换为特定于平台的格式。

void ExamplePath::processFillPath()
{
    if (processingDone)
        return;

    PlatformInterface::PointF current(0.0, 0.0);

    PlatformInterface::PathDataIterator it(path);

    while (it.hasNext()) {
        PlatformInterface::PathDataSegment segment = it.next();
        switch (segment.type()) {
        case PlatformInterface::PathData::CloseSegment:
            addElement(static_cast<int32_t>(HW_PATH_CLOSE));
            break;
        case PlatformInterface::PathData::PathSeparatorSegment:
            break;
        case PlatformInterface::PathData::MoveSegment: {
            const PlatformInterface::PathDataMoveSegment *moveSegment
                = segment.as<PlatformInterface::PathDataMoveSegment>();
            addElement(static_cast<int32_t>(HW_PATH_MOVETO));
            addElement(moveSegment->target().x());
            addElement(moveSegment->target().y());
            current = moveSegment->target();
            break;
        }
        case PlatformInterface::PathData::LineSegment: {
            const PlatformInterface::PathDataLineSegment *lineSegment
                = segment.as<PlatformInterface::PathDataLineSegment>();
            addElement(static_cast<int32_t>(HW_PATH_LINETO));
            addElement(lineSegment->target().x());
            addElement(lineSegment->target().y());
            current = lineSegment->target();
            break;
        }
        case PlatformInterface::PathData::QuadraticBezierSegment: {
            const PlatformInterface::PathDataQuadraticBezierSegment *bezierSegment
                = segment.as<PlatformInterface::PathDataQuadraticBezierSegment>();
            // ...
            break;
        }
        case PlatformInterface::PathData::CubicBezierSegment: {
            const PlatformInterface::PathDataCubicBezierSegment *bezierSegment
                = segment.as<PlatformInterface::PathDataCubicBezierSegment>();
            // ...
            break;
        }
        case PlatformInterface::PathData::SmallCounterClockWiseArcSegment: {
            const PlatformInterface::PathDataSmallCounterClockWiseArcSegment *arcSegment
                = segment.as<PlatformInterface::PathDataSmallCounterClockWiseArcSegment>();
            // ...
            break;
        }
        case PlatformInterface::PathData::SmallClockWiseArcSegment: {
            const PlatformInterface::PathDataSmallClockWiseArcSegment *arcSegment
                = segment.as<PlatformInterface::PathDataSmallClockWiseArcSegment>();
            // ...
            break;
        }
        case PlatformInterface::PathData::LargeCounterClockWiseArcSegment: {
            const PlatformInterface::PathDataLargeCounterClockWiseArcSegment *arcSegment
                = segment.as<PlatformInterface::PathDataLargeCounterClockWiseArcSegment>();
            // ...
            break;
        }
        case PlatformInterface::PathData::LargeClockWiseArcSegment: {
            const PlatformInterface::PathDataLargeClockWiseArcSegment *arcSegment
                = segment.as<PlatformInterface::PathDataLargeClockWiseArcSegment>();
            // ...
            break;
        }
        default:
            QUL_ASSERT(false, QulError_PathData_UnknownSegmentType, segment.type());
            return;
        }
    }

    addElement(static_cast<int32_t>(HW_PATH_END));
    processingDone = true;
}

路径分配

接下来,实现PlatformInterface::DrawingEngine::allocatePath 函数,该函数在分配路径句柄时会被调用。

PlatformInterface::DrawingEngine::Path *ExampleDrawingEngine::allocatePath(const PlatformInterface::PathData *pathData,
                                                                           PlatformInterface::PathFillRule fillRule)
{
    return PlatformInterface::qul_new<Private::ExamplePath>(pathData, fillRule);
}

路径与绘图设备的融合

接下来应实现PlatformInterface::DrawingEngine::blendPath 函数。(这需要您按照“硬件加速混合”中的描述创建一个自定义绘图引擎。) 当路径即将通过transform 和blendMode 渲染到绘图设备上时,会调用此函数。结果必须由clipRect 进行裁剪,该坐标系为绘图设备坐标系。此外,sourceOpacity 定义了总不透明度,其取值范围为0到256,其中256表示完全不透明。

  • 如果未将fillBrush 设置为nullptr ,则路径将根据分配路径时设定的PathFillRule ,使用给定的fillBrush 进行填充。
  • 如果strokeBrush 未设置为nullptr ,则路径将根据分配路径时设置的StrokeProperties ,使用给定的strokeBrush 进行描边。setStrokeProperties 。
void ExampleDrawingEngine::blendPath(PlatformInterface::DrawingDevice *drawingDevice,
                                     PlatformInterface::DrawingEngine::Path *path,
                                     const PlatformInterface::Transform &transform,
                                     const PlatformInterface::Rect &clipRect,
                                     const PlatformInterface::Brush *fillBrush,
                                     const PlatformInterface::Brush *strokeBrush,
                                     int sourceOpacity,
                                     PlatformInterface::DrawingEngine::BlendMode blendMode)
{
    Private::ExamplePath *destinationPath = static_cast<Private::ExamplePath *>(path);

    float matrix[3][3];
    toHwMatrix3x3(transform, matrix);

    // HW_SetClip(clipRect.x(), clipRect.y(), clipRect.width(), clipRect.height());

    // HW_BlendMode_t HWblendMode =
    //     (blendMode == PlatformInterface::DrawingEngine::BlendMode_SourceOver ? HW_BLEND_SRC_OVER : HW_BLEND_NONE);

    if (fillBrush) {
        destinationPath->processFillPath();

        // HW_Path_t hw_path = {..., destinationPath->fillPathSize(), destinationPath->getFillPathData(), ...};

        if (fillBrush->pattern() == Qul::PlatformInterface::Brush::LinearGradientPattern) {
            const Qul::PlatformInterface::GradientStops &gradientStops = fillBrush->linearGradient().stops();
            // HW_GradientColorTable_Handle hw_gradientColorTable = nullptr;
            // hw_gradientColorTable = generateHW_GradientColorTable(gradientStops);

            // HW_DrawWithLinearGradient(..., &hw_path, destinationPath->fillRule, &matrix, HWblendMode, hw_gradientColorTable, hwLinearGradientParameters(fillBrush->linearGradient()), ...);

            // As an optimization it might make sense to keep a cache of HW gradient color tables
            // if (hw_gradientColorTable)
            //     freeHW_GradientColorTable(hw_gradientColorTable);
        } else if (fillBrush->pattern() == Qul::PlatformInterface::Brush::SolidPattern) {
            // HW_Draw(..., &hw_path, destinationPath->fillRule, &matrix, HWblendMode, fillBrush->color().value, ...);
        }
    }

    if (strokeBrush) {
        // HW_Path_t hw_path = {..., destinationPath->strokePathSize(), destinationPath->getStrokePathData(), ...};

        if (strokeBrush->pattern() == Qul::PlatformInterface::Brush::LinearGradientPattern) {
            const Qul::PlatformInterface::GradientStops &gradientStops = fillBrush->linearGradient().stops();
            // HW_GradientColorTable_Handle hw_gradientColorTable = nullptr;
            // hw_gradientColorTable = generateHW_GradientColorTable(gradientStops);

            // HW_DrawWithLinearGradient(..., &hw_path, destinationPath->fillRule, &matrix, HWblendMode, hw_gradientColorTable, hwLinearGradientParameters(strokeBrush->linearGradient()), ...);

            // As an optimization it might make sense to keep a cache of HW gradient color tables
            // if (hw_gradientColorTable)
            //     freeHW_GradientColorTable(hw_gradientColorTable);
        } else if (strokeBrush->pattern() == Qul::PlatformInterface::Brush::SolidPattern) {
            // HW_Draw(..., &hw_path, destinationPath->fillRule, &matrix, HWblendMode, strokeBrush->color().value, ...);
        }
    }

    // HW_SetClip(0, 0, screen->width(), screen->height());
}

路径描边

最后,实现Qul::PlatformInterface::DrawingEngine::setStrokeProperties 函数。可以通过Qul::PlatformInterface::StrokeProperties 访问LineCapStyle 和MiterLimit 等描边属性。

void ExampleDrawingEngine::setStrokeProperties(PlatformInterface::DrawingEngine::Path *path,
                                               const PlatformInterface::StrokeProperties &strokeProperties)
{
    Private::ExamplePath *destinationPath = static_cast<Private::ExamplePath *>(path);
    ...
}

生成用于描边的路径

Qul::PlatformInterface::PathDataStroker 可用于根据给定路径创建描边轮廓路径。当平台驱动程序接口不支持描边属性时,此方法非常有用。通过继承PathDataStroker 并重写以下函数来使用该函数:

class ExamplePathDataStroker : public PlatformInterface::PathDataStroker
{
public:
    ExamplePathDataStroker(ExamplePath *data);

protected:
    void beginStroke() QUL_DECL_OVERRIDE;
    void endStroke() QUL_DECL_OVERRIDE;
    void lineTo(float x, float y) QUL_DECL_OVERRIDE;
    void moveTo(float x, float y) QUL_DECL_OVERRIDE;
    void cubicTo(float c1x, float c1y, float c2x, float c2y, float ex, float ey) QUL_DECL_OVERRIDE;
    void arcTo(float x, float y, float rx, float ry, float rotation, bool largeArc, bool clockwise) QUL_DECL_OVERRIDE;

private:
    ExamplePath *destinationPath;
    PlatformInterface::PointF current;
};

为每个函数实现支持,以便以适合该平台的优化格式填充路径数据。这将生成一个代表笔画的路径并对其进行填充。

ExamplePathDataStroker::ExamplePathDataStroker(ExamplePath *data)
    : PathDataStroker(data->getPathData())
    , destinationPath(data)
{}

void ExamplePathDataStroker::beginStroke()
{
    destinationPath->clearStroke();
}

void ExamplePathDataStroker::endStroke()
{
    destinationPath->addStrokeElement(static_cast<int32_t>(HW_PATH_END));
}

void ExamplePathDataStroker::lineTo(float x, float y)
{
    destinationPath->addStrokeElement(static_cast<int32_t>(HW_PATH_LINETO));
    destinationPath->addStrokeElement(x);
    destinationPath->addStrokeElement(y);
    current.setX(x);
    current.setY(y);
}

void ExamplePathDataStroker::moveTo(float x, float y)
{
    destinationPath->addStrokeElement(static_cast<int32_t>(HW_PATH_MOVETO));
    destinationPath->addStrokeElement(x);
    destinationPath->addStrokeElement(y);
    current.setX(x);
    current.setY(y);
}

void ExamplePathDataStroker::cubicTo(float c1x, float c1y, float c2x, float c2y, float ex, float ey)
{
    // ...
    current.setX(ex);
    current.setY(ey);
}

void ExamplePathDataStroker::arcTo(float x, float y, float rx, float ry, float rotation, bool largeArc, bool clockwise)
{
    // ...
    current.setX(x);
    current.setY(y);
}

可以在Qul::PlatformInterface::DrawingEngine::setStrokeProperties 函数中预先计算笔画路径。

void ExampleDrawingEngine::setStrokeProperties(PlatformInterface::DrawingEngine::Path *path,
                                               const PlatformInterface::StrokeProperties &strokeProperties)
{
    Private::ExamplePath *destinationPath = static_cast<Private::ExamplePath *>(path);

    Private::ExamplePathDataStroker stroker(destinationPath);
    stroker.setStrokeProperties(strokeProperties);
    stroker.stroke();
}

在某些 Qt 许可证下可用。
了解更多。