在游戏制作的过程中经常会使用到提示,常见的方法是通过jni调用android下的方法实现toast提示
通过cocos2dx的LayerColor可以实现如上功能
1、头文件Toast.h
#pragma once
#include "cocos2d.h"
USING_NS_CC;
class Toast : public Layer {
public:
Toast();
~Toast();
virtual bool init();
CREATE_FUNC(Toast);
static Toast* create(const char* text, int fontsize = 30, float time = 1);
private:
//设置文字
void setText(const char* text, int fontsize, float time);
//设置背景
void setBackgound();
//删除
void removeSelf();
private:
LayerColor *m_backgound;
Label *m_label;
};
2、实现Toast.cpp
#include "Toast.h"
Toast::Toast(void)
{
}
Toast::~Toast(void)
{
}
bool Toast::init()
{
if (!Layer::init()) {
return false;
}
//设置大小与显示位置
this->setContentSize(Size::ZERO);
auto size = Director::getInstance()->getVisibleSize();
Vec2 pos = Vec2(size.width / 2, 70);
this->setPosition(pos);
return true;
}
//创建弹出提示框
Toast* Toast::create(const char* text, int fontsize, float time)
{
Toast* toast = Toast::create();
toast->setLocalZOrder(INT_MAX);
toast->setText(text, fontsize, time);
toast->setBackgound();
return toast;
}
//设置文字
void Toast::setText(const char* text, int fontsize, float time)
{
m_label = Label::createWithSystemFont(text, "", fontsize);
this->addChild(m_label, 3);
Sequence * ation = Sequence::create(ScaleTo::create(time, 1.0), CallFunc::create(CC_CALLBACK_0(Toast::removeSelf, this)), NULL);
this->runAction(ation);
}
//设置背景
void Toast::setBackgound(){
m_backgound = LayerColor::create(Color4B(0, 0, 0, 0));
this->addChild(m_backgound, 2);
m_backgound->ignoreAnchorPointForPosition(false);
m_backgound->setContentSize(Size::ZERO);
m_backgound->setAnchorPoint(Vec2(0.5f, 0.5f));
m_backgound->setOpacity(150);
if (m_label){
Size size = Size(m_label->getContentSize().width + m_label->getSystemFontSize(), m_label->getContentSize().height + m_label->getSystemFontSize() / 2);
m_backgound->setContentSize(size);
m_backgound->setPosition(m_label->getPosition());
}
}
//移除Toast
void Toast::removeSelf(){
this->removeFromParentAndCleanup(true);
}
3、使用方式
auto toast = Toast::create("你好");
this->addChild(toast)
9525



被折叠的 条评论
为什么被折叠?



