CCScrollView 和 CCLabelTTF 组成CCScrollLabel
在一些项目中,经常会遇到文本很长,但是美术设计的对话框又不够大,以至于文本溢出对话框(如任务描述文字等)。为解决这个创建问题,本人写了一个CCScrollLabel,此类实现一个可以滚动查看文本的窗口。CCScrollLabel是基于cocos2d-x-2.0.4版本的。另外特别注意:cocos2d-x-2.0.3版本的CCScrollView有很大缺陷,建议基于该版本的游戏项目不要使用该CCScrollView。或者将项目中CCScrollView替换成至少2.0.4版本的。
其实这个功能实现起来应该说是很容易的,但是网上CCScrollView的资料手册不多。这里比较详细的说明一下2.0.4版本下的CCScrollView的各项特性:
//// XJScrollLabel.cpp//// Created by jason on 13-1-30.//#include "XJScrollLabel.h"XJScrollLabel* XJScrollLabel::create(const char *pszText, const char *fontName, float fontSize, CCTextAlignment hAlignment, cocos2d::CCSize ScrollViewSize){XJScrollLabel* pScrollLabel = new XJScrollLabel;if( pScrollLabel && pScrollLabel->init( pszText, fontName, fontSize, hAlignment, ScrollViewSize ) ){pScrollLabel->autorelease();return pScrollLabel;}else{CC_SAFE_DELETE( pScrollLabel );return NULL;}}XJScrollLabel::XJScrollLabel() :m_pScrollView( NULL ),m_pLabel( NULL ){}XJScrollLabel::~XJScrollLabel(){CC_SAFE_RELEASE_NULL( m_pLabel );CC_SAFE_RELEASE_NULL( m_pScrollView );}bool XJScrollLabel::init(const char *pszText, const char *fontName, float fontSize, CCTextAlignment hAlignment, cocos2d::CCSize& ScrollViewSize){//object has been initialized.if( m_pScrollView || m_pLabel ){return false;}//constraint the label's width, but not height.m_pLabel = CCLabelTTF::create( pszText, fontName, fontSize, CCSizeMake( ScrollViewSize.width, 0 ), hAlignment );m_pLabel->retain();//get the texture sizeCCSize TextSize = m_pLabel->getTexture()->getContentSize();//we have to invoke CCScrollView::create( ScrollViewSize ) instead of //CCScrollView::create( ScrollViewSize, m_pLabel ) to let the CCScrollView//create a default container for you.//It's because that the label may smaller than the view of//CCScrollView. If that is the condition, the label will be positioned//at the bottom of the View by CCScrollView. //Even though you can set the label at the top, but the behavior of//ScrollView always try to reposition it. So we must ensure the container//is larger than the View of CCScrollView.m_pScrollView = CCScrollView::create( ScrollViewSize );m_pScrollView->retain();m_pScrollView->setDelegate( this );m_pScrollView->setDirection( kCCScrollViewDirectionVertical );//set the container size.//So we must ensure the conainer is larger than the View of CCScrollView.if( TextSize.height > ScrollViewSize.height ){m_pScrollView->setContentSize( TextSize );//make the left-top corner of container coincide with View'sm_pScrollView->setContentOffset( ccp( 0, ScrollViewSize.height - TextSize.height ) );}else{m_pScrollView->setContentSize( ScrollViewSize );}//put the label at the top of the container.m_pScrollView->addChild( m_pLabel );m_pLabel->ignoreAnchorPointForPosition( false );m_pLabel->setAnchorPoint( ccp( 0, 1 ) );m_pLabel->setPosition( ccp( 0, m_pScrollView->getContentSize().height ) );addChild( m_pScrollView );return true;}