Browse Source

pie图图例文字超长自动换行逻辑

zhuth 7 years ago
parent
commit
aa6a6c2bfb
1 changed files with 58 additions and 0 deletions
  1. 58 0
      kanban-client/app/component/converter.js

+ 58 - 0
kanban-client/app/component/converter.js

@@ -454,6 +454,18 @@ function pieConfig(model) {
     pieconfig = parseObjectStr(pieconfig);
     pieconfig = parseObjectStr(pieconfig);
     series = series ? ((series instanceof Array) ? series : [series]) : [];
     series = series ? ((series instanceof Array) ? series : [series]) : [];
     series = series.map((v, i) => {
     series = series.map((v, i) => {
+        v.name += '';
+        let textWidth = getTextViewWidth(v.name, fontSize || getFontSize() * 0.7);
+        v.name = v.name.replace(/\n/g,'');
+        if(legendconfig.orient == 'vertical' && legendconfig.width) {
+            legendconfig.itemWidth = legendconfig.itemWidth ? Number(legendconfig.itemWidth) : 25;
+            legendconfig.itemGap = legendconfig.itemGap ? Number(legendconfig.itemGap) : layout.w / 10;
+            let availableWidth = Number(legendconfig.width) - legendconfig.itemWidth - legendconfig.itemGap;
+            if(availableWidth >0 && textWidth > availableWidth) {
+                fontSize = fontSize || getFontSize() * 0.7;
+                v.name = wrapText(v.name, fontSize, availableWidth)
+             }
+        }
         v.value = v.data;
         v.value = v.data;
         return v;
         return v;
     });
     });
@@ -784,4 +796,50 @@ function getFontSize() {
     return fontSize;
     return fontSize;
 }
 }
 
 
+/**
+ * 获得文本展示后的高宽
+ */
+function getTextViewWidth(text, fontSize) {
+    let sp = document.createElement('span');
+    sp.innerText = text;
+    sp.style.fontSize = fontSize + 'px';
+    sp.style.opacity = 0;
+    document.getElementById('root').appendChild(sp);
+    let width = sp.getBoundingClientRect().width;
+    document.getElementById('root').removeChild(sp);
+    return width;
+}
+
+/**
+ * 换行逻辑
+ */
+function wrapText(text, fontSize, width) {
+    text = text.replace(/\n/g,'');
+    let start = 0, splitCount = 0, splitIndexs = [];
+    for(let i = 0; i < text.length; i++) {
+        let st = text.substring(start, i);
+        if(getTextViewWidth(st) >= width) {
+            splitIndexs.push(i);
+            start = i;
+        }
+    }
+    for(let j = 0; j < splitIndexs.length; j++) {
+        text = text.insert('\n', splitIndexs[j] + splitCount);
+        splitCount ++;
+    }
+    if(text.charAt(text.length - 1) == '\n') {
+        text = text.substring(0, text.length - 1);
+    }
+    
+    return text;
+
+}
+String.prototype.insert = function(str, index){
+    let newstr = "";             //初始化一个空字符串
+    let tmp = this.substring(0, index);
+    let estr = this.substring(index, this.length);
+    newstr += tmp + str + estr;
+    return newstr;
+}
+
 export { converter };
 export { converter };