2013-08-05 46 views
0

我想得到這個代碼與loadStrings();如何獲得此代碼與loadStrings();工作?

現在代碼通過加載文本字符串字符串=,我想改變它,爲了讓它讀取.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

轉到素描 - >添加文件來添加文本文件,然後使用此代碼從文本文件中的字符串:

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)); 
} 

注意,在這個例子中,整個字符串是在文本文件的第一行。如果你想從其他行獲得字符串,那麼你需要訪問「行」數組的不同部分。

+0

@Scarnix一個快速說明,你不應該a)聲明字符串數組,也不b)在draw()循環中加載文件。正確的實現將是全局聲明它,在setup()中加載它,然後在draw()中迭代它... –