Using TextRange we access text stored in text frames. And through characterAttributes
we access character properties by index: textRange.characters[idx].characterAttributes
.
Problem
Found bug replacing text color if TextFrame contained many colors. The case is specific. Let’s create a text object without changing its dimensions. We save the old color of some character into a variable, assign the new color to the text, and then paint the text in the color of the saved character.
var oldColor = selection[0].textRange.characters[0].characterAttributes.fillColor;
var newColor = new RGBColor();
newColor.red = 255;
selection[0].textRange.characterAttributes.fillColor = newColor;
redraw();
var msg = 'First character color: ' + oldColor.red + ' ';
msg += newColor.blue + ' ' + newColor.green + '\nTemp color: ';
msg += newColor.red + ' ' + newColor.blue + ' ' + newColor.green;
alert(msg);
selection[0].textRange.characterAttributes.fillColor = oldColor;
redraw();
The text will be partially colored. But we ran the command on the full TextRange.
Solution
Experimentally, I found that the problem is similar to the Paragraph panel script bugs in the note “Forced change of paragraph properties” and the solution method is the same. If you change the text frame scale, the problem is solved. If the text in the document has already been scaled manually before running the script, there is no bug. There is no logical explanation for this Illustrator problem.
The code fixes this by inserting the native resize()
method.
var oldColor = selection[0].textRange.characters[0].characterAttributes.fillColor;
var newColor = new RGBColor();
newColor.red = 255;
selection[0].textRange.characterAttributes.fillColor = newColor;
redraw();
selection[0].resize(200, 200); // fix recolor bug
selection[0].textRange.characterAttributes.fillColor = oldColor;
selection[0].resize(50, 50); // fix recolor bug
redraw();