同一字段中的字体大小不同

时间:2013-02-09 16:45:14

标签: blackberry user-interface java-me paint

如何在同一字段中使用不同字体大小的paint方法(使用字段扩展)获取文本。??

1 个答案:

答案 0 :(得分:4)

如果你真的想通过改变被覆盖的paint()方法中的字体大小来做到这一点,你可以使用这样的东西:

   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);
   }

请注意,我必须创建字段NON_FOCUSABLE,因为如果您通过更改paint()中的字体来欺骗字段,则蓝色光标将与基础文本不匹配。您也可以通过覆盖drawFocus()并不执行任何操作来删除光标。

你没有指定任何焦点要求,所以我不知道你想要什么。

如果您愿意考虑其他替代方案,我认为RichTextField更适合让您在同一字段中更改字体大小(或其他文本属性)。如果你想要的只是逐渐缩小文本,就像我的例子那样,这个paint()实现可能就好了。如果您想在字段中选择某些字词来绘制更大的字体(例如使用HTML <span>标签),那么RichTextField可能是最佳方式。

以下是我的示例代码的输出:

enter image description here

相关问题