Cocos2dx-截屏并设置图片尺寸
猴子原创,欢迎转载。转载请注明: 转载自Cocos2D开发网–Cocos2Dev.com,谢谢。
原文地址: http://www.cocos2dev.com/?p=522
前几天加入微信图片分享的时候,发现全屏截图超出了微信的数据包大小,所以截屏的时候能够考虑缩小尺寸到0.5倍。
以下的截屏代码:
void LHUtil::screenShoot()
{
Size visibleSize = Director::getInstance()->getVisibleSize();
//定义一个屏幕大小的渲染纹理
RenderTexture* renderTexture = RenderTexture::create(visibleSize.width * .5, visibleSize.height * .5, Texture2D::PixelFormat::RGBA8888);
Scene* curScene = Director::getInstance()->getRunningScene();
Point ancPos = pCurScene->getAnchorPoint();
//渲染纹理開始捕捉
renderTexture->begin();
// 缩小屏幕截屏区域
curScene->setScale(.5);
curScene->setAnchorPoint(cocos2d::Point(0, 0));
//绘制当前场景
curScene->visit();
//结束
renderTexture->end();
//保存png
renderTexture->saveToFile("screenshoot.png", Image::Format::PNG);
// 恢复屏幕尺寸
curScene->setScale(1);
curScene->setAnchorPoint(ancPos);
CC_SAFE_DELETE(curScene);
}
上面是cocos2dx的获取截屏的方法。
我顺便写下怎样用OC的UIGraphicsBeginImageContext获取UIView转化成UIImage.
以下是ios方法:
-(void)screenShot:(CGRect)rect{
// 開始设置截屏区域
UIGraphicsBeginImageContextWithOptions(rect.size, YES, 0);
[[self.view layer] renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// 获取image。能够依据须要进行尺寸改动
CGImageRef imageRef = viewImage.CGImage;
CGImageRef imageRefRect =CGImageCreateWithImageInRect(imageRef, rect);
UIImage *image = [[UIImage alloc] initWithCGImage:imageRefRect];
// 保存图片到相冊, 这里会提示用户授权。不须要保存的话。能够取消
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
// 获取Documents文件夹
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:@"temScreenShot.png"];
// 保存image到Documents文件夹
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:YES];
CGImageRelease(imageRefRect);
}