在cocos2d-x开发包的test程序中有了截屏的例子,根据这个再加了一点内容:可以随意截取屏幕的某个部分,之后保存图片,两种格式,图片也能显示在屏幕。
http://download.csdn.net/detail/xexiyong/5720369
void HelloWorld::ccTouchesBegan(CCSet* pTouches, CCEvent* pEvent)
{
CCSetIterator kIterator = pTouches->begin();
CCTouch* pTouch = (CCTouch*)(*kIterator);
//按下触屏时记录开始触屏点
m_kBeginPos = pTouch->locationInView( pTouch->view() );
m_kBeginPos = CCDirector::sharedDirector()->convertToGL( m_kBeginPos );
}
记录开始触屏的点,然后,记录离开触屏的点,经过计算:
void HelloWorld::ccTouchesEnded(CCSet* pTouches,CCEvent* pEvent)
{
CCSetIterator kIterator = pTouches->begin();
CCTouch* pTouch = (CCTouch*)(*kIterator);
m_kEndPos = pTouch->locationInView( pTouch->view() );
m_kEndPos = CCDirector::sharedDirector()->convertToGL( m_kEndPos );
//针对开始点与结束点的计算,得到定制的矩形
CRectMake(m_kBeginPos,m_kEndPos);
CCSize size = CCDirector::sharedDirector()->getWinSize();
//定义一个屏幕大小的渲染纹理
CCRenderTexture* pScreen = CCRenderTexture::renderTextureWithWidthAndHeight(size.width,size.height);
//获得当前的场景指针
CCScene* pCurScene = CCDirector::sharedDirector()->getRunningScene();
//渲染纹理开始捕捉
pScreen->begin();
//当前场景参与绘制
pCurScene->visit();
//结束捕捉
pScreen->end(false);
//保存为png(经过裁切的)
pScreen->saveBuffer(kCCImageFormatPNG, "Print.png",
m_kRect.origin.x, m_kRect.origin.y,
m_kRect.size.width, m_kRect.size.height);
//保存为jpg,经过裁切的
pScreen->saveBuffer(kCCImageFormatJPG,"Print.jpg",
m_kRect.origin.x, m_kRect.origin.y,
m_kRect.size.width, m_kRect.size.height);
//得到该渲染纹理,将该纹理转为精灵经过裁切显示出来
CCSprite* pTempImage = CCSprite::spriteWithTexture(
(pScreen->getSprite())->getTexture(),
m_kRect);
pTempImage->setPosition(ccp(0,0));
//Y翻转
pTempImage->setFlipY(true);
addChild(pTempImage,1);
//结束且释放
CC_SAFE_DELETE(pScreen);
}
其中,CRectMake函数作用是利用开始点与结束点算出矩形的宽高和基本点,以供文件生成和精灵显示 使用。
void HelloWorld::CRectMake(CCPoint point1,CCPoint point2)
{
CCPoint kOriginPoint;
if (point1.x < point2.x)
{
if (point1.y < point2.y)
{
kOriginPoint.x = point1.x;
kOriginPoint.y = point2.y;
}
else
{
kOriginPoint = point1;
}
}
else
{
if (point1.y < point2.y)
{
kOriginPoint = point2;
}
else
{
kOriginPoint.x = point2.x;
kOriginPoint.y = point1.y;
}
}
//至此确定左上角点(是左下角点,cocos2d以左下为基准)
m_kRect = CCRect(kOriginPoint.x,kOriginPoint.y - abs(point1.y - point2.y),abs(point1.x - point2.x),abs(point1.y - point2.y));
}
最终效果很生硬。大家去优化。