Skip to content

Instantly share code, notes, and snippets.

@camila314
Last active January 12, 2025 12:05
Show Gist options
  • Select an option

  • Save camila314/76bea1a181fcf366c71d3711dfc2bcdf to your computer and use it in GitHub Desktop.

Select an option

Save camila314/76bea1a181fcf366c71d3711dfc2bcdf to your computer and use it in GitHub Desktop.
SVGNode implementation in Geode
// CPMAddPackage("gh:sammycage/lunasvg#master")
// target_link_libraries(${PROJECT_NAME} lunasvg)
#include <Geode/Geode.hpp>
#include <lunasvg.h>
using namespace geode::prelude;
class SvgNode : public CCNode {
CCSprite* m_rendered = nullptr;
std::unique_ptr<lunasvg::Document> m_document;
public:
static SvgNode* create(char const* svgData, CCSize const& size) {
auto pRet = new SvgNode();
if (pRet && pRet->CCNode::init()) {
if (pRet->init(svgData, size)) {
pRet->autorelease();
return pRet;
}
}
CC_SAFE_DELETE(pRet);
return NULL;
}
bool init(char const* svgData, CCSize const& size) {
m_document = lunasvg::Document::loadFromData(svgData);
setAnchorPoint({0.5, 0.5});
render(size);
return true;
}
void setContentSize(CCSize const& size) override {
render(size);
}
protected:
void render(CCSize const& size) {
if (m_rendered) {
m_rendered->removeFromParent();
}
auto scaleFactor = CCDirector::sharedDirector()->getContentScaleFactor();
auto width = size.width < 0 ? size.width : size.width * scaleFactor;
auto height = size.width < 0 ? size.width : size.height * scaleFactor;
auto bitmap = m_document->renderToBitmap(width, height);
bitmap.convertToRGBA();
CCNode::setContentSize(CCSizeMake(bitmap.width() / scaleFactor, bitmap.height() / scaleFactor));
auto texture = new CCTexture2D();
texture->initWithData(bitmap.data(), kCCTexture2DPixelFormat_RGBA8888, bitmap.width(), bitmap.height(), CCSizeMake(bitmap.width(), bitmap.height()));
texture->m_bHasPremultipliedAlpha = false;
m_rendered = CCSprite::createWithTexture(texture);
m_rendered->setAnchorPoint({0, 0});
addChild(m_rendered);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment