final int[] highlightLength) {
final int x = rect.x;
final int y = rect.y;
final int textWidth = rect.width;
final Font oldFont = g.getFont();
final Font font = g.getFont();
final Font highlightFont =
font.derive(font.isBold() ? Font.EXTRA_BOLD : Font.BOLD);
try {
// Just draw the text normally if there's no highlight region
final int numHighlightStartIndexes =
highlightStartIndex == null ? 0
: highlightStartIndex.length;
if (numHighlightStartIndexes == 0) {
g.setFont(oldFont);
g.drawText(text, 0, text.length(), x, y, DrawStyle.ELLIPSIS,
textWidth);
return;
}
int textStartIndex = 0;
int offsetX = 0;
boolean hasEndText = true;
/**
* <pre>
* Text Highlight Algorithm
*
* Given the set of highlightStartIndex values and the
* highlightLength values, we already know exactly which
* portions of the text need to be highlighted and how many
* characters to highlight.
*
* The algorithm below uses the aforementioned values to
* determine the highlighted and non-highlighted regions of
* text. Then in a single pass through the text, it draws the
* text regions as required.
*
* The text highlighting algorithm works as follows by iterating
* through the set of highlight indexes and performing the required
* text highlighting operations. These operations are as follows:
*
* 1. Calculate the start index for the current portion of the text
* to draw.
*
* 2. Determine if the start index for the text to draw is
* equal to the current highlight index. If it's not equal,
* the characters from the start index to the current highlight
* index are not highlighted. If it is equal, then the amount of
* characters to highlight is dictated by the highlight length.
*
* 3. Draw the text before the current highlight index in a
* non-highlighted font.
*
* 4. Draw the text from the highlight index to the
* highlight index + highlight length in a highlighted font.
* Repeat steps 1 to 4 until the last highlight region is drawn.
*
* 5. There may be text after the last highlight index that hasn't
* been drawn. Therefore, there is a check to see if there is
* any such text and if so, it is drawn in the non-highlighted font.
* </pre>
*/
int i = 0;
for (i = 0; i < numHighlightStartIndexes; i++) {
if (i != 0) {
// Calculate the start index for current portion of the
// text to draw.
textStartIndex =
highlightStartIndex[i - 1] + highlightLength[i - 1];
}
// Draw the text before the highlight region
if (highlightStartIndex[i] != textStartIndex) {
g.setFont(oldFont);
g.drawText(text, textStartIndex, highlightStartIndex[i]
- textStartIndex, x + offsetX, y, 0, textWidth
- offsetX);
}
// Draw the highlighted text
offsetX +=
oldFont.getAdvance(text, textStartIndex,
highlightStartIndex[i] - textStartIndex);
g.setFont(highlightFont);
g.drawText(text, highlightStartIndex[i], highlightLength[i], x
+ offsetX, y, 0, textWidth - offsetX);
final int nextOffsetX =
highlightFont.getAdvance(text, highlightStartIndex[i],
highlightLength[i]);
offsetX += nextOffsetX;
}
i--;