-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathSVGSprite.cpp
68 lines (61 loc) · 1.78 KB
/
SVGSprite.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include "SVGSprite.h"
USING_NS_CC;
SVGSprite* SVGSprite::create(std::string path, float scale, std::string unit, float dpi)
{
SVGSprite* ref = new (std::nothrow) SVGSprite();
if(ref && ref->init(path, scale, unit, dpi))
{
ref->autorelease();
return ref;
}else
{
CC_SAFE_DELETE(ref);
ref = nullptr;
return nullptr;
}
}
bool SVGSprite::init(std::string path, float scale, std::string unit, float dpi)
{
std::ostringstream os;
os << path << "_" << scale << "_" << unit << "_" << dpi;
Texture2D* texture = TextureCache::getInstance()->getTextureForKey(os.str());
if(texture != nullptr) return Sprite::initWithTexture(texture);
else {
NSVGimage *image = NULL;
NSVGrasterizer *rast = NULL;
unsigned char* img = NULL;
int w, h;
//--- parse svg from file
image = nsvgParseFromFile(path.c_str(), unit.c_str(), dpi);
if (image == NULL) {
log("Could not open SVG image.\n");
nsvgDeleteRasterizer(rast);
nsvgDelete(image);
return false;
}
//--- init rasterizer
w = (int)image->width * scale;
h = (int)image->height * scale;
rast = nsvgCreateRasterizer();
if (rast == NULL) {
log("Could not init Rasterizer.\n");
nsvgDeleteRasterizer(rast);
nsvgDelete(image);
return false;
}
//--- create image buffer
img = (unsigned char*)malloc(w*h * 4);
if (img == NULL) {
log("Could not alloc image buffer.\n");
nsvgDeleteRasterizer(rast);
nsvgDelete(image);
return false;
}
log("rasterizing image %d x %d\n", w, h);
nsvgRasterize(rast, image, 0, 0, scale, img, w, h, w * 4);
Image* imageA = new Image();
imageA->initWithRawData(img, w*h * 4, w, h, 4);
texture = TextureCache::getInstance()->addUIImage(imageA, os.str());
return Sprite::initWithTexture(texture);
}
}