如何使用loadStrings();?

时间:2013-08-05 14:22:22

标签: string text load processing

我想让这段代码与loadStrings();

一起使用

现在代码通过 String string = 加载文本,我想改变它,以使其读取.txt文件。

我尝试了各种方法,但我似乎总是得到错误代码。有可能吗?

PFont font;
String string = "Processing is an open source programming language and environment for people who want to program images, animation, and interactions.";
int fontSize = 10;
int specificWidth = 150;
int lineSpacing = 2;

int textHeight;

void setup() {
  size(600,600);
  background(0);

  font = createFont("Times New Roman", fontSize);
  textFont(font,fontSize);
  noLoop();
}

void draw() {
  fill(60);
  stroke(60);
  rect(100,100,specificWidth, calculateTextHeight(string, specificWidth, fontSize, lineSpacing));
  fill(255);
  text(string, 100,100,specificWidth,1000);
}

int calculateTextHeight(String string, int specificWidth, int fontSize, int lineSpacing) {
  String[] wordsArray;
  String tempString = "";
  int numLines = 0;
  float textHeight;

  wordsArray = split(string, " ");

  for (int i=0; i < wordsArray.length; i++) {
    if (textWidth(tempString + wordsArray[i]) < specificWidth) {
 tempString += wordsArray[i] + " ";
    }
    else {
 tempString = wordsArray[i] + " ";
 numLines++;
    }
  }

  numLines++; //adds the last line

  textHeight = numLines * (textDescent() + textAscent() + lineSpacing);
  return(round(textHeight));
} 

1 个答案:

答案 0 :(得分:1)

转到草图 - &gt;添加文件以添加文本文件,然后使用此代码从文本文件中获取字符串:

PFont font;
String string = "";
int fontSize = 10;
int specificWidth = 150;
int lineSpacing = 2;
String lines[];

int textHeight;

void setup() {
  size(600,600);

  lines[] = loadStrings("text.txt");

  font = createFont("Times New Roman", fontSize);
  textFont(font,fontSize);
  noLoop();
}

void draw() {
  background(0);
  string = lines[0];
  fill(60);
  stroke(60);
  rect(100,100,specificWidth, calculateTextHeight(string, specificWidth, fontSize, lineSpacing));
  fill(255);
  text(string, 100,100,specificWidth,1000);
}

int calculateTextHeight(String string, int specificWidth, int fontSize, int lineSpacing) {
  String[] wordsArray;
  String tempString = "";
  int numLines = 0;
  float textHeight;

  wordsArray = split(string, " ");

  for (int i=0; i < wordsArray.length; i++) {
    if (textWidth(tempString + wordsArray[i]) < specificWidth) {
 tempString += wordsArray[i] + " ";
    }
    else {
 tempString = wordsArray[i] + " ";
 numLines++;
    }
  }

  numLines++; //adds the last line

  textHeight = numLines * (textDescent() + textAscent() + lineSpacing);
  return(round(textHeight));
} 

请注意,在此示例中,整个字符串位于文本文件的第一行。如果你想从其他行获取字符串,那么你需要访问“lines”数组的不同部分。