如何将 CCSprite 保存为 PNG

发布于 2024-12-04 03:32:57 字数 1169 浏览 1 评论 0原文

我创建了 CCSprite 并将其添加到主视图中。 然后我想看到精灵图像,所以我将其保存为PNG 但其中很多都没有正确保存。 只显示白色背景。 我不知道原因,也通过谷歌找到了一些文章,但它们根本没有帮助我。 我该如何解决这个问题?

CCSprite *sprite = [[CCSprite spriteWithFile:[NSString stringWithUTF8String:name] rect:CGRectMake(startx, starty, w, h)] retain];

float drawX = x, drawY = y; 

CGSize size = [sprite contentSize];

int nWidth = size.width;
int nHeight = size.height;
nWidth *= scale;
nHeight *= scale;
drawX = drawX + nWidth/2;
drawY = drawY - nHeight/2;

ConvertCoordf(&drawX, &drawY);
drawY -= nHeight;
[sprite setScale:scale];
[sprite setPosition:ccp(drawX, drawY)];
[_mainLayer addChild:sprite];

CCRenderTexture* render = [CCRenderTexture renderTextureWithWidth:sprite.contentSize.width height:sprite.contentSize.height];    
[render begin];
[sprite visit];
[render end];    
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString  *pngPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"new%d.png",i]];
i++;
[render saveBuffer:pngPath format:kCCImageFormatPNG];

[sprite release];

I created CCSprite and add it to the main view.
Then I want to see the sprite image, so I saved it to PNG
But lots of them doesn't saved correctly.
Only show white background.
I can't know the reason, and also found some articles via Google, but they didn't help me at all.
How can I solve this?

CCSprite *sprite = [[CCSprite spriteWithFile:[NSString stringWithUTF8String:name] rect:CGRectMake(startx, starty, w, h)] retain];

float drawX = x, drawY = y; 

CGSize size = [sprite contentSize];

int nWidth = size.width;
int nHeight = size.height;
nWidth *= scale;
nHeight *= scale;
drawX = drawX + nWidth/2;
drawY = drawY - nHeight/2;

ConvertCoordf(&drawX, &drawY);
drawY -= nHeight;
[sprite setScale:scale];
[sprite setPosition:ccp(drawX, drawY)];
[_mainLayer addChild:sprite];

CCRenderTexture* render = [CCRenderTexture renderTextureWithWidth:sprite.contentSize.width height:sprite.contentSize.height];    
[render begin];
[sprite visit];
[render end];    
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString  *pngPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"new%d.png",i]];
i++;
[render saveBuffer:pngPath format:kCCImageFormatPNG];

[sprite release];

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文