Tutorial Request:Randomize Each Character Color in text
-
Hi, I want to to write a bit of code that randomly changes the the color of each character in a block of text to a different color from a preselected pallet of colors. I've figured out the code to randomly select a color from a predefined pallet, and I figured out how to split all the characters in a raw txt document into a list of individual characters, but I'm at a loss as to how to apply the two principles together to color each character in a block of text individually. Any help or suggestions are much welcomed.
Heres the code I have so far:w=1000 h=1000 newPage(w,h) colors=[(.349,.306,.251),(.576,.612,.255),(.961,.753,.031),(.851,.302,.196),(0,.702,.788)] import random fileName = 'toBeOrNot.txt' textFile = open(fileName,"r") wordText = textFile.read() textFile.close() box = (350,300,400,400) myFont = 'Skia-Regular' pointSize = 20 lst=[x for x in wordText] print(lst) r,g,b= random.choice(colors) fill(r,g,b) font(myFont, pointSize) textBox(wordText,box,align="left")
Thanks in advance!
-
you will need to use a loop to iterate over your list of characters and append them to a formattedString.
first initiate the
formattedString
:f_str = FormattedString(font = myFont, fontSize = pointSize)
then iterate over your list:
for ch in wordText:
select a random color inside the loop and append the character to the
formattedString
ch_col = random.choice(colors) f_str.append(ch, fill = ch_col)
finally draw your
textBox
with theformattedString
textBox(f_str, box, align="left")
so the last four lines of your code should be:
f_str = FormattedString(font = myFont, fontSize = pointSize) for ch in wordText: ch_col = random.choice(colors) f_str.append(ch, fill = ch_col) textBox(f_str, box, align="left")
good luck!
-
Thank you!