From df5bbe3dfce0abcdfa6fda76391ca1f94d78aaaa Mon Sep 17 00:00:00 2001 From: Volodymyr Zvarun Date: Sun, 7 Apr 2024 20:48:38 +0300 Subject: [PATCH] Add render child element --- include/lunasvg.h | 2 ++ source/lunasvg.cpp | 30 ++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/include/lunasvg.h b/include/lunasvg.h index b7cdbcb..85759fe 100644 --- a/include/lunasvg.h +++ b/include/lunasvg.h @@ -198,6 +198,8 @@ class LUNASVG_API DomElement { */ Element* get() { return m_element; } + Bitmap renderToBitmap(std::uint32_t width, std::uint32_t height, std::uint32_t backgroundColor = 0x00000000) const; + private: Element* m_element = nullptr; }; diff --git a/source/lunasvg.cpp b/source/lunasvg.cpp index 549d3ca..cba4bab 100644 --- a/source/lunasvg.cpp +++ b/source/lunasvg.cpp @@ -335,6 +335,36 @@ Matrix DomElement::getAbsoluteTransform() const return getLocalTransform(); } +Bitmap DomElement::renderToBitmap(std::uint32_t width, std::uint32_t height, std::uint32_t backgroundColor) const { + if(m_element == nullptr || !m_element->box()) + return Bitmap(); + + auto elementBounds = m_element->box()->map(m_element->box()->strokeBoundingBox()); + if(elementBounds.empty()) + return Bitmap(); + + if(width == 0 && height == 0) { + width = static_cast(std::ceil(elementBounds.w)); + height = static_cast(std::ceil(elementBounds.h)); + } else if(width != 0 && height == 0) { + height = static_cast(std::ceil(width * elementBounds.h / elementBounds.w)); + } else if(height != 0 && width == 0) { + width = static_cast(std::ceil(height * elementBounds.w / elementBounds.h)); + } + + const auto xScale = width / elementBounds.w; + const auto yScale = height / elementBounds.h; + + Matrix matrix(xScale, 0, 0, yScale, -elementBounds.x * xScale, -elementBounds.y * yScale); + Bitmap bitmap(width, height); + bitmap.clear(backgroundColor); + RenderState state(nullptr, RenderMode::Display); + state.canvas = Canvas::create(bitmap.data(), bitmap.width(), bitmap.height(), bitmap.stride()); + state.transform = Transform(matrix); + m_element->box()->render(state); + return bitmap; +} + std::unique_ptr Document::loadFromFile(const std::string& filename) { std::ifstream fs;