首页 > 代码库 > Cocos2d-x计算字符串Size方法

Cocos2d-x计算字符串Size方法

项目需要,根据输入字符串,计算字符串所需要占的Size。封装代码如下,只需传入字符串,即可返回Size:

Size ChartDemoScene::calculateFontSize(const char *str )
{
	std::string tempString = str;
	log("tempString = %s",tempString.c_str());
	size_t computeCount = tempString.size();       //如果字符串很长每次抽取100个字符来计算size;
	Size size = Size(0,0);
	for (int i = 0; i<computeCount ;)
	{
        std::string substring =  tempString.substr(i,1);
		if ((substring.c_str()[0] & 0x80 )!=0) //是汉字
		{
			substring = tempString.substr(i , 3);
			i += 3;
		}
		else
		{
			i++;
		}
		//CCLog("subString  = %s ",substring.c_str());
        auto tempLabel = LabelTTF::create(substring.c_str(),"",25);
        tempLabel->setHorizontalAlignment(cocos2d::TextHAlignment::LEFT);
		Size tmpLsize = tempLabel->getContentSize();
		size.width+=tmpLsize.width;
	}
    
	float fHeight= 0;
	if( size.width > chartWidth)//大于容器的宽度
	{
        fHeight = (size.width / 200 );//计算需要多少行
	}
	int nHeight =  ceil(fHeight);
	
	if (nHeight == 0)
	{
		nHeight = 1;
	}
    
	Size labelSize ;
	if (size.width < chartWidth)
	{
		labelSize = Size(size.width,nHeight*32);//计算容器的Size
	}
	else
	{
        labelSize = Size(chartWidth,nHeight*28);
	}
	
	//CCLog("labelSize = (%f, %f)",labelSize.width ,labelSize.height);
	//CCLog("fHeight = %f  nHeight = %d " ,fHeight ,nHeight);
	return labelSize;
}

例子:

1、AppDelegate.cpp中添加如下代码

auto scene = ChartDemoScene::createScene();

    // run
    director->runWithScene(scene);
(1)ChartDemoScene.hChartDemoScene.h
//
//  ChartDemoScene.h
//  chartDemo
//
//  Created by chen on 14-9-2.
//
//

#ifndef __chartDemo__ChartDemoScene__
#define __chartDemo__ChartDemoScene__

#include "cocos2d.h"
#include "ui/CocosGUI.h"
#include "../cocos2d/extensions/cocos-ext.h"
using namespace cocos2d::ui;
USING_NS_CC;
USING_NS_CC_EXT;

class ChartDemoScene : public cocos2d::Layer//,public cocos2d::extension::EditBoxDelegate
{
public:
    // there's no 'id' in cpp, so we recommend returning the class instance pointer
    static cocos2d::Scene* createScene();
    
    // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
    virtual bool init();
    
    // a selector callback
    void menuCloseCallback(cocos2d::Ref* pSender);
    
    // implement the "static create()" method manually
    CREATE_FUNC(ChartDemoScene);
    
//    virtual void editBoxEditingDidBegin(cocos2d::extension::EditBox* editBox);
//    virtual void editBoxEditingDidEnd(cocos2d::extension::EditBox* editBox);
//    virtual void editBoxTextChanged(cocos2d::extension::EditBox* editBox, const std::string& text);
//    virtual void editBoxReturn(cocos2d::extension::EditBox* editBox);

    void touchEvent(Ref *pSender, Widget::TouchEventType type);
    void textFieldEvent(Ref* pSender, TextField::EventType type);
    void showAlertShow(std::string contentString);
    void alertCallback(ui::Text* alert);
    
    Size calculateFontSize(const char *str);
    
    std::string getcurrTime();//获取当前年月日
    std::string getcurrMonthTime();//获取时分秒

//    EditBox* editText;
    TextField* editText;
    Text* text;
    TextField* _text;//获取被删除Item的内容
    std::string file_path;//存放消息记录
    TextField* textContent;
    ui::Button* sendBtn;
    std::string str;
    Size winSize;
    float chartWidth;
    size_t length;
    ui::ListView* _listView;
    
};
#endif /* defined(__chartDemo__ChartDemoScene__) */

(2)ChartDemoScene.cpp

#include "ChartDemoScene.h"
#include "stdio.h"

enum alertTag
{
    Alert_Tag = 1000
    
}AlertTag;

enum textTag
{
    T_Tag = 100
}TextTag;

USING_NS_CC;
int count = 1;
int _rem = 0;
Scene* ChartDemoScene::createScene()
{
    // 'scene' is an autorelease object
    auto scene = Scene::create();
    scene->setColor(Color3B::BLACK);
    // 'layer' is an autorelease object
    auto layer = ChartDemoScene::create();
    layer->setAnchorPoint(Vec2::ANCHOR_MIDDLE_BOTTOM);
    layer->setContentSize(Size(640,960));
    // add layer as a child to scene
    scene->addChild(layer);
    
    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool ChartDemoScene::init()
{
    bool bRet = false;
    do{
        CC_BREAK_IF(!Layer::init());
        //大背景
        winSize = Director::getInstance()->getWinSize();
        file_path = FileUtils::getInstance()->getWritablePath() + "chartContent.txt";
        
        chartWidth = winSize.width *3 / 5;
        auto sprite = Sprite::create("orange_edit.png");
        sprite->setScaleX(winSize.width / sprite->getContentSize().width);
        sprite->setScaleY(winSize.height / sprite->getContentSize().height);
        sprite->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
        sprite->setPosition(Vec2(winSize.width/2,winSize.height/2));
        addChild(sprite);
        
        auto layerColor = LayerColor::create(Color4B(43, 177, 233, 255));
        layerColor->setContentSize(Size(winSize.width,100));
        layerColor->ignoreAnchorPointForPosition(false);
        layerColor->setAnchorPoint(Vec2::ANCHOR_MIDDLE_TOP);
        layerColor->setPosition(Vec2(winSize.width/2,winSize.height));
        addChild(layerColor,4);
        
        //底部输入栏
        auto layout = Layout::create();
        layout->setSize(Size(winSize.width,100));
        layout->setAnchorPoint(Vec2::ZERO);
        layout->setPosition(Vec2::ZERO);
        layout->setBackGroundColorType(cocos2d::ui::Layout::BackGroundColorType::SOLID);
        layout->setBackGroundColor(Color3B(185,185,185));
        //消息显示栏
        _listView = ListView::create();
        _listView->setDirection(ui::ScrollView::Direction::VERTICAL);
        _listView->setTouchEnabled(true);
        _listView->setBounceEnabled(true);
        _listView->setGravity(cocos2d::ui::ListView::Gravity::BOTTOM);
//        _listView->setItemsMargin(2);
        _listView->setBackGroundColorType(cocos2d::ui::Layout::BackGroundColorType::SOLID);
        _listView->setBackGroundColor(Color3B::WHITE);
        _listView->setSize(Size(winSize.width,winSize.height-layout->getSize().height-25-100));
        _listView->setAnchorPoint(Vec2::ANCHOR_MIDDLE_BOTTOM);
        _listView->setPosition(Vec2(winSize.width/2,layout->getSize().height+25));
        addChild(_listView);
        
        //底部输入框背景
        auto bg = Sprite::create("whitebg.png");
        bg->setScaleX(winSize.width*3/5 / bg->getContentSize().width);
        bg->setScaleY(80 / bg->getContentSize().height);
        bg->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);
        bg->setPosition(Vec2(winSize.width/5,layout->getSize().height/2));
        layout->addChild(bg);
        
        //
        editText = TextField::create("","",30);
        editText->ignoreContentAdaptWithSize(false);
        editText->setSize(Size(winSize.width*3/5,80));
        editText->setTextHorizontalAlignment(cocos2d::TextHAlignment::LEFT);
        editText->setTextVerticalAlignment(cocos2d::TextVAlignment::BOTTOM);
        editText->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);
        editText->setPosition(Vec2(winSize.width/5,layout->getSize().height/2));
        editText->setColor(Color3B::BLACK);
        editText->addEventListener(CC_CALLBACK_2(ChartDemoScene::textFieldEvent, this));
        layout->addChild(editText);
        addChild(layout);
        
        //发送按钮
        sendBtn = ui::Button::create("orange_edit.png");
        sendBtn->setAnchorPoint(Vec2::ANCHOR_MIDDLE_RIGHT);
        sendBtn->setPosition(Vec2(winSize.width - 20,layout->getSize().height/2));
        addChild(sendBtn);
        
        sendBtn->addTouchEventListener(CC_CALLBACK_2(ChartDemoScene::touchEvent,this));
        
        auto alert_Text = ui::Text::create();
        alert_Text->setSize(Size(50, 200));
        alert_Text->setTag(Alert_Tag);
        alert_Text->setOpacity(0);
        alert_Text->setFontSize(35);
        char* userdata = http://www.mamicode.com/"11";>



Cocos2d-x计算字符串Size方法