【问题标题】:How to draw a string to the screen character by character如何逐个字符地将字符串绘制到屏幕上
【发布时间】:2019-03-21 11:37:06
【问题描述】:

我有下面的代码在从字符串中绘制字符之间产生延迟,这可以使用 println() 但是在使用 text() 函数时不起作用。代码应该等待分配的时间然后打印下一个字符,我真的不确定我做错了什么。

int startTimer;
int waitTime = 500;
boolean funcRun = true;

void setup(){
 size(500, 500);
 startTimer = millis();
}

void draw(){
  while(funcRun){
    textAnim("hello");
  }
}

void textAnim(String textInput){
int counter = 0;
int x = 10;

while(counter < textInput.length()){
    if(millis() - startTimer>waitTime){
      text(textInput.charAt(counter), x , 100);
       startTimer = millis();
       ++counter;
       x = x + 10;
    }
    funcRun = false;
  }
}

【问题讨论】:

    标签: string loops animation text processing


    【解决方案1】:

    显示的屏幕在draw() 函数结束时更新。因此,您的 while 循环已完全执行,并显示了完整的文本。您必须修改代码,使其不断刷新/重绘屏幕,并根据时间循环更新显示的文本。

    例如这样:

    int currentTime;
    int waitTime = 500;
    int characters_to_display = 0;
    boolean stringComplete = false;
    
    String textInput = "Hello"; 
    
    void setup() {
      size(500, 500);
      currentTime = millis();
    }
    
    void draw() {
      // Update text to be shown. increaseCharIndex() is called while the text is not yet fully displayed
      if (stringComplete == false) {
        increaseCharIndex();
      }
    
      //Draw screen:
    
      // draw background to clear screen
      background(0);
      // display (a substring of) the text
      text(textInput.substring(0, characters_to_display), 10, 100);
    }
    
    void increaseCharIndex() {
      // if the waitperiod has passed, increase the number of characters to be displayed
      if (millis() - currentTime>waitTime) {
        currentTime = millis();
        characters_to_display++;
      }    
      // if the full text will be shown, end the call to increaseCharIndex()
      if (characters_to_display >= textInput.length())
      {
        stringComplete = true;
      }
    }
    

    【讨论】:

    • 谢谢!这很有意义。
    猜你喜欢
    • 2017-08-18
    • 2013-01-18
    • 1970-01-01
    • 2014-04-02
    • 2021-12-10
    • 2013-01-18
    • 1970-01-01
    • 2012-03-06
    • 1970-01-01
    相关资源
    最近更新 更多