【Cocos2dx】使用CCScale9Sprite拉伸图片

如下图,在资源的Rescources文件夹中自带一个40×40的按钮图片

如果我们在Cocos2dx设定此图片自动拉伸为填充游戏屏幕的800×600图片,如下图:

总不能在外部利用Photoshop等图形处理软件,自行把这张40×40的图片拉伸为800×600,然后根据不同的设备的分辨率,做多张图片吧?

此时可以利用Cocos2dx的CCScale9Sprite。

CCScale9Sprite不属于Cocos2dx的基本类,但一般的Cocos2dx已经引入这个类了。

部分Cocos2dx可能需要与《【Cocos2dx】资源文件夹,播放背景音乐,,导入外部库》(点击打开链接)一样,添加Cocos2dx安装文件夹下的extensions目录,之后通过【右击工程】->【属性】->【配置属性】->【链接器】->【输入】,编辑【附加依赖项】,自行补上libExtensions.lib,把这个基本包补上,但大部分的Cocos2dx只要在要实现的场景cpp中引入#include "cocos-ext.h"这个头文件就可以使用CCScale9Sprite。

像《【Cocos2dx】Windows平台下Cocos2dx 2.x的下载、安装、配置,打造自己的Helloworld》(点击打开链接)一样,在AppDelegate.cpp关闭程序的调试信息,同时在main.cpp将程序设定尺寸大小为800×600,对HelloWorldScene.cpp引入#include "cocos-ext.h"这个头文件,同时将其bool HelloWorld::init(){}方法修改,得到如下代码:

#include "HelloWorldScene.h"#include "cocos-ext.h"USING_NS_CC;CCScene* HelloWorld::scene(){// 'scene' is an autorelease objectCCScene *scene = CCScene::create();// 'layer' is an autorelease objectHelloWorld *layer = HelloWorld::create();// add layer as a child to scenescene->addChild(layer);// return the scenereturn scene;}// on "init" you need to initialize your instancebool HelloWorld::init(){//获取屏幕的尺寸、位置信息等CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();cocos2d::extension::CCScale9Sprite *scale9Sprite = cocos2d::extension::CCScale9Sprite::create("CloseSelected.png");//声明要拉伸的图片scale9Sprite->setContentSize(CCSize(visibleSize.width,visibleSize.height));//设置图片的大小拉伸至整个屏幕这么大scale9Sprite->setPosition(ccp(origin.x + visibleSize.width/2,origin.y + visibleSize.height/2));//图片的中心点位于屏幕的中央this->addChild(scale9Sprite);//把图片放上场景return true;}void HelloWorld::menuCloseCallback(CCObject* pSender){#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)CCMessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");#elseCCDirector::sharedDirector()->end();#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)exit(0);#endif#endif}就可以把一张原本为40×40的图片尽可能地拉伸,如上图,成为了一张还不算太难看的800×600的背景图片了。其中CCScale9Sprite位于cocos2d::extension这个命名空间。

版权声明:本文为博主原创文章,未经博主允许不得转载。

把艰辛的劳作看作是生命的必然,

【Cocos2dx】使用CCScale9Sprite拉伸图片

相关文章:

你感兴趣的文章:

标签云: