• ‎Cocos2d-x 学习笔记(18) Label


    1. 简介

    Label直接继承了Node LabelProtocol BlendProtocol,用于渲染文本,让文本呈现的效果丰富。

    Label有4种类型,:

        enum class LabelType {
            TTF,
            BMFONT,
            CHARMAP,
            STRING_TEXTURE
        };

    Label文本呈现的效果:

    enum class LabelEffect {
        NORMAL,
        OUTLINE,
        SHADOW,
        GLOW,
        ITALICS,
        BOLD,
        UNDERLINE,
        STRIKETHROUGH,
        ALL
    };

    针对Label大小范围与文本长度冲突时的4种操作,用枚举定义:

        enum class Overflow
        {
            //In NONE mode, the dimensions is (0,0) and the content size will change dynamically to fit the label.
            NONE,
            /**
             *In CLAMP mode, when label content goes out of the bounding box, it will be clipped.
             */
            CLAMP,
            /**
             * In SHRINK mode, the font size will change dynamically to adapt the content size.
             */
            SHRINK,
            /**
             *In RESIZE_HEIGHT mode, you can only change the width of label and the height is changed automatically.
             */
            RESIZE_HEIGHT
        };

    1

    2. 构造函数

    从构造函数得知:

    锚点(0.5,0.5)

    调用reset()方法

    LabelType默认STRING_TEXTURE

    LabelEffect默认NORMAL

    设置了默认字体和大小

    label长宽大小默认0

    对齐方式默认LEFT TOP

    文本颜色默认白色,效果颜色默认黑色

    Overflow默认NONE 

    3. create

    create()

    创建空的label对象和指针。

    createWithSystemFont

    Label* createWithSystemFont(const std::string& text, const std::string& font, float fontSize,
            const Size& dimensions = Size::ZERO, TextHAlignment hAlignment = TextHAlignment::LEFT,
            TextVAlignment vAlignment = TextVAlignment::TOP)

    共6个参数:

    • string& text 要显示的字符串
    • string& font 字体,字体名/字体文件
    • float fontSize 字体大小,必须大于0
    • Size& dimensions = Size::ZERO label大小,默认Size(0, 0)
    • TextHAlignment hAlignment = TextHAlignment::LEFT 水平对齐方式,默认左对齐
    • TextVAlignment vAlignment = TextVAlignment::TOP 垂直对齐方式,默认顶部对齐

    实现:

        auto ret = new (std::nothrow) Label(hAlignment,vAlignment);
        if (ret)
        {
            ret->setSystemFontName(font);
            ret->setSystemFontSize(fontSize);
            ret->setDimensions(dimensions.width, dimensions.height);
            ret->setString(text);
    
            ret->autorelease();
    
            return ret;
        }
        return nullptr;

    通过set方法用参数进行set。

    • setSystemFontName
      _systemFont设为参数字体
      _currentLabelType = LabelType::STRING_TEXTURE
      _systemFontDirty = true

    • setSystemFontSize 
      _systemFontSize _originalFontSize 设为参数字体大小
      _currentLabelType = LabelType::STRING_TEXTURE;
      _systemFontDirty = true  

    • setDimensions
      如果Overflow为RESIZE_HEIGHT类型,先将参数height设0

      _labelWidth = width;
      _labelHeight = height;
      _labelDimensions.width = width;
      _labelDimensions.height = height;
      _maxLineWidth = width; //最大文本宽度

      _contentDirty = true;

      如果Overflow是SHRINK类型,

        if (_originalFontSize > 0) {
                this->restoreFontSize();
            }

    • setString
      _utf8Text _utf32Text 都存储了set的字符串

    createWithTTF

    有2种重载方法:

    • 方法1:参数中用string& fontFilePath指定字符串字体文件.ttf路径
      Label * createWithTTF(const std::string& text, const std::string& fontFilePath, float fontSize,
              const Size& dimensions = Size::ZERO, TextHAlignment hAlignment = TextHAlignment::LEFT,
              TextVAlignment vAlignment = TextVAlignment::TOP)

      参数中没有ttf,利用参数生成对应的ttf,之后调用了setTTFConfig(ttfConfig)
      还调用了setDimensions(dimensions.width, dimensions.height); setString(text);

    • 方法2:参数中用TTFConfig设置字体,maxLineWidth值为最大文本行宽(默认为0, 表示不设置)
      Label* createWithTTF(const TTFConfig& ttfConfig, const std::string& text, 
              TextHAlignment hAlignment = TextHAlignment::LEFT, int maxLineWidth = 0)

        对参数ttfConfig调用了setTTFConfig(ttfConfig),之后执行setMaxLineWidth(maxLineWidth); setString(text);

    字体配置TTFConfig是一个结构体:

    typedef struct _ttfConfig
    {
        std::string fontFilePath; //字体文件路径,默认空
        float fontSize; //字体大小,默认12
    
        GlyphCollection glyphs; //字符集,默认DYNAMIC
        const char *customGlyphs; //自定义字符集, 默认无
    
        bool distanceFieldEnabled; //是否字体紧凑,默认false
        int outlineSize; //字体轮廓大小,默认0
    
        bool italics; //是否斜体,默认false
        bool bold; //是否粗体,默认false
        bool underline; //是否有下划线,默认false
        bool strikethrough; //是否有删除线,默认false
    
        _ttfConfig(..........)
            : fontFilePath(filePath)
            , fontSize(size)
            , glyphs(glyphCollection)
            , customGlyphs(customGlyphCollection)
            , distanceFieldEnabled(useDistanceField)
            , outlineSize(outline)
            , italics(useItalics)
            , bold(useBold)
            , underline(useUnderline)
            , strikethrough(useStrikethrough)
        {
            if(outline > 0)
            {
                distanceFieldEnabled = false;
            }
        }
    } TTFConfig;

    setTTFConfig(ttfConfig)

    先执行_originalFontSize = ttfConfig.fontSize

    再调用setTTFConfigInternal(ttfConfig)

    _currentLabelType = LabelType::TTF

    createWithBMFont

    参数中包括BMFont软件生成的.fnt文件路径和显示的文本。字符串必须和.fnt文件定义的文本一致,否则多余的不显示。

    Label* createWithBMFont(const std::string& bmfontPath, const std::string& text,
            const TextHAlignment& hAlignment = TextHAlignment::LEFT, int maxLineWidth = 0,
            const Vec2& imageOffset = Vec2::ZERO)

    调用了setBMFontFilePath(bmfontFilePath,imageOffset),_currentLabelType = LabelType::BMFONT

    调用了setMaxLineWidth(maxLineWidth) setString(text);

    我们使用BMFont能生成自定义字体,软件导出.fnt字体信息文件和.png字体图片文件,两文件放在同一目录被Cocos2dx使用。

    createWithCharMap

    有三种重载方法:

    Label * createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap)
    Label * createWithCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap)
    Label * createWithCharMap(const std::string& plistFile)

    创建方式分为三种:

    • 通过.png图片文件
    • 通过Texture2D纹理
    • 通过.plist文件

    前两种方式要在参数中设置表示字符的每个小图的长宽、起始的下标值startCharMap(ASCII,用'0'代替48)。.plist则已经包含了这些参数。

    每种重载都调用了对应的setCharMap,其中调用了对应的FontAtlasCache::getFontAtlasCharMap生成newAtlas,再执行

      _currentLabelType = LabelType::CHARMAP
      setFontAtlas(newAtlas)

    - TTF BMFont CharMap

    TTF统一配置字体属性,对label中所有文本都有效。

    BMFont需要.fnt .png文件,使用时仅需要.fnt路径,.fnt类似于.plist,通过文本内容选择大图.png中对应的字符。

    CharMap可以看作BMFont的简化版,通过ASCII读取大图里不同的字符。

    4. 渲染特效

    Label提供了三种字体特效:

    • Shadow 阴影
    • Outline 描边
    • Glow 发光

    三种特效设置方式:

    enableShadow(const Color4B& shadowColor = Color4B::BLACK,const Size &offset = Size(2,-2), int blurRadius = 0)
    enableOutline(const Color4B& outlineColor,int outlineSize = -1)
    enableGlow(const Color4B& glowColor)

    描边Outline和发光Glow只支持createWithTTF创建的label。且两者同时使用时,仅后设置的显示。

    阴影Shadow的Size是以label的左上角为基准点设置阴影的位置的。

    5. 对齐方式

    Label默认的对齐方式是LEFT+TOP。

    分为水平方向和竖直方向,对应Label两个成员:

        TextHAlignment _hAlignment; //水平
        TextVAlignment _vAlignment; //竖直

    定义两个枚举:

    enum class CC_DLL TextVAlignment
    {
        TOP,
        CENTER,
        BOTTOM
    };
    
    enum class CC_DLL TextHAlignment
    {
        LEFT,
        CENTER,
        RIGHT
    };

    相关set get方法:

        void setAlignment(TextHAlignment hAlignment) { setAlignment(hAlignment,_vAlignment);}
        TextHAlignment getTextAlignment() const { return _hAlignment;}
        void setAlignment(TextHAlignment hAlignment,TextVAlignment vAlignment);
    void setHorizontalAlignment(TextHAlignment hAlignment) { setAlignment(hAlignment,_vAlignment); } TextHAlignment getHorizontalAlignment() const { return _hAlignment; }
    void setVerticalAlignment(TextVAlignment vAlignment) { setAlignment(_hAlignment,vAlignment); } TextVAlignment getVerticalAlignment() const { return _vAlignment; }

    6. 范围大小

    label所处的文本框大小,涉及变量:

        Size _labelDimensions;
        float _labelWidth;
        float _labelHeight;

    相关get set方法:

        void setWidth(float width) { setDimensions(width,_labelHeight);}
        float getWidth() const { return _labelWidth; }
    
        void setHeight(float height){ setDimensions(_labelWidth, height); }
        float getHeight() const { return _labelHeight; }
    
        void setDimensions(float width, float height);
        const Size& getDimensions() const{ return _labelDimensions;}

    设置尺寸使用setDimensions,而不是Node的setContentSize。setDimensions主要逻辑:

    _labelWidth = width;
    _labelHeight = height;
    _labelDimensions.width = width;
    _labelDimensions.height = height;
    _maxLineWidth = width;

    -

    7. 文本 字体 大小 颜色

        virtual void setSystemFontName(const std::string& font);
        virtual const std::string& getSystemFontName() const { return _systemFont;}
    
        virtual void setSystemFontSize(float fontSize);
        virtual float getSystemFontSize() const { return _systemFontSize;}
    
        virtual void setString(const std::string& text) override;
        virtual const std::string& getString() const override {  return _utf8Text;  }
     
    //仅ttf systemfont
      virtual void setTextColor(const Color4B &color);
      const Color4B& getTextColor() const { return _textColor;}

    -

    8. 自动换行 行间距

    - void setLineBreakWithoutSpace(bool breakWithoutSpace)

    是否开启换行功能,设置了属性_lineBreakWithoutSpaces。

    - void setMaxLineWidth(float maxLineWidth)

    设置最大行宽,需要_labelWidth为0时才能继续设置,否则我们仅通过_labelWidth就能实现自动换行。设置了属性_maxLineWidth。

    - label尺寸相关

    涉及到_labelDimensions _labelWidth _labelHeight。

        void setWidth(float width) { setDimensions(width,_labelHeight);}
        float getWidth() const { return _labelWidth; }
    
        void setHeight(float height){ setDimensions(_labelWidth, height); }
        float getHeight() const { return _labelHeight; }
    
        void setDimensions(float width, float height);
        const Size& getDimensions() const{ return _labelDimensions;}

    - void setLineHeight(float height) / float getLineHeight()

    直接修改属性_lineHeight。行间距不支持System Font。

    - void setAdditionalKerning(float space) / float getAdditionalKerning()

    字符间距修改属性_additionalKerning,不支持System Font。

    -

  • 相关阅读:
    增量更新代码步骤记录
    软件缺陷管理基本流程
    数据库语言(三):MySQL、PostgreSQL、JDBC
    eclipse的使用
    数据库语言(二):SQL语法实例整理
    windows下MySql没有setup.exe时的安装方法
    数学:完全独立于实际场景的情况下定义的概念,可以正确的描述世界
    数学语言和程序语言的对比:面向过程与面向集合&命题
    iOS开发之IMP和SEL(方法和类的反射)
    iOS之UIButton的normal和selected状态切换
  • 原文地址:https://www.cnblogs.com/deepcho/p/cocos2dx-label.html
Copyright © 2020-2023  润新知