Cocos2dx 3.X Label的换行

来源:互联网 发布:ext ajax 参数类型json 编辑:程序博客网 时间:2024/06/03 23:07
很多项目中都会有Label换行的需求,之前自己还手动写了个换行的处理。但才发现3.X引擎已经帮我们做了这件事。而且用法很简单针对LabelTTF(如果你用的ccui.Text,调用getVirtualRenderer(),返回值就是labelTTF)再对LabelTTF调用setDimensions方法即可,来看下源码
/**     * Set Dimensions of cc.LabelTTF, the dimension is the maximum size of the label, set it so that label will automatically change lines when necessary.     * @param {cc.Size|Number} dim dimensions or width of dimensions     * @param {Number} [height] height of dimensions     */    setDimensions: function (dim, height) {        var width;        if (height === undefined) {            width = dim.width;            height = dim.height;        } else            width = dim;        if (width !== this._dimensions.width || height !== this._dimensions.height) {            this._dimensions.width = width;            this._dimensions.height = height;            this._updateString();            // Force update            this._setUpdateTextureDirty();        }    },
用例,setDimensions(50,60)或者setDimensions(cc.size(50,60));50表示尺寸的宽,60表示高;针对需要换行的一般只考虑宽就行了,高度给一个够用的就行,如果规定了有几行,你也可以确定高度。然后在调整对齐方式和锚点就能达到你想要的效果。如下:[换行效果]![这里写图片描述](http://img.blog.csdn.net/20170525110446627?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvaWFtbGVnZW5kYXJ5/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)两个Label宽度一样,cocos还考虑了不拆分单词,很人性,应该是根据空格做的处理。