天天看點

【Cocos2dx】使用CCScale9Sprite拉伸圖檔

如下圖,在資源的Rescources檔案夾中自帶一個40x40的按鈕圖檔

【Cocos2dx】使用CCScale9Sprite拉伸圖檔

如果我們在Cocos2dx設定此圖檔自動拉伸為填充遊戲螢幕的800x600圖檔,如下圖:

【Cocos2dx】使用CCScale9Sprite拉伸圖檔

總不能在外部利用Photoshop等圖形處理軟體,自行把這張40x40的圖檔拉伸為800x600,然後根據不同的裝置的分辨率,做多張圖檔吧?

此時可以利用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将程式設定尺寸大小為800x600,對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 object
    CCScene *scene = CCScene::create();
    
    // 'layer' is an autorelease object
    HelloWorld *layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool 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");
#else
    CCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
#endif
}
           

就可以把一張原本為40x40的圖檔盡可能地拉伸,如上圖,成為了一張還不算太難看的800x600的背景圖檔了。其中CCScale9Sprite位于cocos2d::extension這個命名空間。

繼續閱讀