ツタンラーメンの忘備録

プログラミングや精神疾患、ラーメンについて書いていきます。たぶん。

Processing いい感じに改行 文字枠

Processingでhtml的に幅を指定していい感じに改行した上で,その文字に背景色をつけたかった.
というわけでそういうことができる感じのclassを作った.なんか汚いけど….

setup(文字の上から枠の外までの余白,左,下,左)
update(テキストボックスの最大幅)
draw(文字開始の左, 文字開始の上) -> 枠の下のy座標を返す

ちなみにtabは消えちゃう(´・ω・`)

f:id:hungrykirby:20180208185434g:plain

RectText tb;

void setup(){
  size(1920, 1024);
  background(255);
  String sampleText = "abcdefghijklmnopqrstuvw\nxyz'012345\t67890@[]ああああああああいうえおかきくけこ劉備早々無限大";
  tb = new RectText(sampleText);
  tb.setup(200, 50, 10, 120); /*top, right, buttom, left*/
}

void draw(){
  background(255);
  tb.update(1000.0);
  float y = tb.draw(mouseX, mouseY);
  ellipse(mouseX, y, 20, 20);
}

class RectText {
  String t;
  String textModified;
  StringList sl;
  float xPos, yPos;
  
  float paddingLeft, paddingRight, paddingButtom, paddingTop;
  
  PFont pF;
  
  float th; //text height
  float le; //leading
  
  int numLines;
  float maxWidth; //max width of text
  
  RectText(String _t){
    pF = loadFont("RictyDiminished-Regular-48.vlw");
    t = _t;
  }
  
  void setup(float pT, float pR, float pB, float pL){
    textFont(pF, 48);
    textAlign( LEFT, TOP );    
    th = textAscent() + textDescent();
    le = 2.0;
    textLeading(th+le);
    noStroke();
    
    paddingTop = pT; paddingRight = pR; paddingButtom = pB; paddingLeft = pL;
  }
  
  void update(float w){
    maxWidth = calcMaxW(t, w);
    sl = wordWrap(t, maxWidth);
    numLines = sl.size();
    textModified = "";
    for(int i = 0; i < numLines; i++){
      textModified += (sl.get(i) + "\n");
    }
  }
  float draw(float x, float y){ /*xとyを開始点として文字を書く*/
    xPos = x; yPos = y;
    fill(0);
    rect(xPos - paddingRight, yPos - paddingTop, maxWidth + paddingRight + paddingLeft, (th+le)*(numLines+0) + paddingTop + paddingButtom);
    fill(255, 0, 0);
    text(textModified, xPos, yPos);
    
    return (th+le)*(numLines+0) + paddingButtom + yPos; //Buttom
  }
  
  StringList wordWrap(String s, float mW) {
    StringList a = new StringList();
    float w = 0;
    int i = 0;
    while (i < s.length()) {
      char c = s.charAt(i);
      String cc = "" + c;
      w += textWidth(cc);
      if(c == '\n'){
        String sub = s.substring(0, i);
        a.append(sub);
        s = s.substring(i + 1, s.length());
        i = 1;
        w = 0;
      }else{
        if (w > mW) {
          String sub = s.substring(0, i);
          a.append(sub);
          s = s.substring(i ,s.length());
          i = 0;
          w = 0;
        } else {
          i++;
        }
      }
    }
    a.append(s);
    return a;
  }
  
  float calcMaxW(String _t, float mW){
    float f = 0;
    if(textWidth(_t) > mW) f = mW;
    else f = textWidth(_t);
    return f;
  }
  
}