yswang0927 commented on issue #16898:
URL: https://github.com/apache/echarts/issues/16898#issuecomment-1111632008

   I use this way: `var gridRect = 
chart.getModel().getComponent('grid').coordinateSystem.getRect();` to get Grid 
dynamic size to solve xAxis label too long.
   ```js
   //打散字符(处理单/双字节字符,2个单字节字符=1个双字节字符)
   function splitChars(s) {
        if (!s) {
                return [''];
        }
        //匹配双字节字符
        var CJKR =/^[^\x00-\xff]+$/;
        var L = s.length;
        var ec = '';
        var ss = [];
        for (var i = 0; i < L; i++) {
                var c = s.charAt(i);
                //亚洲文字
                if (CJKR.test(c)) {
                        if (ec !== '') {
                                ss.push(ec);
                        }
                        ss.push(c);
                        ec = '';
                } else {
                        if (ec.length === 2) {
                                ss.push(ec);
                                ec = '';
                        }
                        ec += c;
                }
        }
        if (ec !== '') {
                ss.push(ec);
                ec = null;
        }
        return ss;
   }
   
   option.xAxis.axisLabel.formatter = function(value, index) {
        var xaxis = chart.getModel().getComponent('xAxis');
        if (!xaxis || 'category' !== xaxis.subType) {
                return value;
        }
        
        var labelsCount = xaxis.getCategories().length;
        if (labelsCount === 0) {
                return value;
        }
        
        var dataZoomModel = chart.getModel().getComponent('dataZoom');
        if (dataZoomModel) {
                var zoomValRange = dataZoomModel.getValueRange();
                labelsCount = (zoomValRange[1] - zoomValRange[0]) + 1;
        }
   
           //用于此次动态获取Grid的可用尺寸
        var rect = 
chart.getModel().getComponent('grid').coordinateSystem.getRect();
        var calcFontSize = parseInt(xaxis.option.axisLabel.fontSize) + 2;
           //计算单个区间最多可以显示的字符个数,并进行自动分割多行展示
        var wordNum = (rect.width / labelsCount) / calcFontSize;
        wordNum = Math.max(parseInt(wordNum), 1);
        var strs = splitChars(value);
        var str = '';
        for (var i = 0, s; s = strs[i++];) {
                str += s;
                if (!(i % wordNum)) {
                        str += '\n';
                }
        }
        return str;
   };
   ```
   Thanks all.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscr...@echarts.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscr...@echarts.apache.org
For additional commands, e-mail: commits-h...@echarts.apache.org

Reply via email to