Vinayak Parmar
Vinayak Parmar

Reputation: 618

Different font size in same field

How can we get text in paint method(extended using field) with different font size in same field.??

Upvotes: 2

Views: 258

Answers (1)

Nate
Nate

Reputation: 31045

If you really want to do this by changing the font size inside the overridden paint() method, you could use something like this:

   public TextScreen() {
      super(MainScreen.VERTICAL_SCROLL | MainScreen.VERTICAL_SCROLLBAR);

      final int MAX_FONT_SIZE = 24;
      // this is the font style to use, but the SIZE will only apply to the 
      //  beginning of the text
      Font f = Font.getDefault().derive(MAX_FONT_SIZE);

      TextField text = new TextField(Field.NON_FOCUSABLE) {
         public void paint(Graphics g) {
            char[] content = getText().toCharArray();

            Font oldFont = g.getFont();
            int size = MAX_FONT_SIZE;
            // use the baseline for the largest font size as the baseline
            //  for all text that we draw
            int y = oldFont.getBaseline();
            int x = 0;
            int i = 0;
            while (i < content.length) {
               // draw chunks of up to 3 chars at a time
               int length = Math.min(3, content.length - i);
               Font font = oldFont.derive(Font.PLAIN, size--);
               g.setFont(font);

               g.drawText(content, i, length, x, y, DrawStyle.BASELINE, -1);

               // skip forward by the width of this text chunk, and increase char index
               x += font.getAdvance(content, i, length);
               i += length;
            }
            // reset the graphics object to where it was
            g.setFont(oldFont);
         }                     
      };

      text.setFont(f);
      text.setText("Hello, BlackBerry font test application!");

      add(text);
   }

Note that I had to make the field NON_FOCUSABLE, because if you trick the field by changing fonts in paint() like this, the blue cursor will not match the underlying text. You could also remove the cursor by overriding drawFocus() and doing nothing.

You didn't specify any focus requirements, so I didn't know what you wanted there.

If you are willing to consider other alternatives, I think the RichTextField is better suited to letting you change font size (or other text properties) within the same field. If all you want is to gradually shrink the text, as my example does, this paint() implementation is probably fine. If you want to select certain words in your field to draw in bigger font (like using HTML <span> tags), then RichTextField is probably the best way to go.

Here's the output of my example code:

enter image description here

Upvotes: 4

Related Questions