Skip to content

Commit

Permalink
Merge pull request #162 from lolpie244/Add-child-element-render
Browse files Browse the repository at this point in the history
Add render child element
  • Loading branch information
sammycage committed Apr 8, 2024
2 parents d1eec96 + df5bbe3 commit 1c989d7
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
2 changes: 2 additions & 0 deletions include/lunasvg.h
Expand Up @@ -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;
};
Expand Down
30 changes: 30 additions & 0 deletions source/lunasvg.cpp
Expand Up @@ -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::uint32_t>(std::ceil(elementBounds.w));
height = static_cast<std::uint32_t>(std::ceil(elementBounds.h));
} else if(width != 0 && height == 0) {
height = static_cast<std::uint32_t>(std::ceil(width * elementBounds.h / elementBounds.w));
} else if(height != 0 && width == 0) {
width = static_cast<std::uint32_t>(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> Document::loadFromFile(const std::string& filename)
{
std::ifstream fs;
Expand Down

0 comments on commit 1c989d7

Please sign in to comment.