Text alteration

For this weeks assignment I decided to further upgrade my scrolling text program. During class time I managed to get it to display a single line of text continuously, with a restriction that the line had to be shorter than the width of the screen. I have upgraded my code, so that now it displays texts of various lengths without any issue. I have also added a new functionality. The input for the news bar is taken directly from a text file, so you can simply type all the great news and they will be displayed automatically.

During coding, the hardest part was to get the moment of switching right. When one string has already left the screen and the other one needs to overwrite the main movement variable OffsetX. This happens when the last letters of the first string leave the screen. I had to add some padding in form of a constant, so that it would appear even smoother.

PFont f;
PImage img;
String myString;
int offsetX;
int textHeight = 370;
int spaceConst = 40;

void setup(){
  size(400, 400);
  f = createFont("Monaco", 40);
  textFont(f);
  myString = "";
  textAlign(LEFT);
  offsetX = width;
  noStroke();
  
  img = loadImage("news.jpg");
  
  String[] lines = loadStrings("text.txt");
  for (int i=0 ; i < lines.length; i++) {
    myString += "| " + lines[i] + " ";
  }
  
  image(img, 0, 0, width, 320);
}

void draw(){
  fill(255,255,0);
  rect(0, 320, width, 80);
  fill(0);
  for (int i=0; i< myString.length(); i++){
    if (offsetX+textWidth(myString) < (width)){
      text(myString.charAt(i), offsetX+textWidth(myString)+spaceConst+textWidth(myString.charAt(i))*i, textHeight);
    }
    text(myString.charAt(i), offsetX+textWidth(myString.charAt(i))*(i+1), textHeight);
    
    if (offsetX+textWidth(myString) < -spaceConst) {
      offsetX = offsetX+int(textWidth(myString))+int(textWidth(myString.charAt(i))*(i+1));
    }
  }
  offsetX -= 2;
}

 

One thought on “Text alteration”

Leave a Reply