2

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

4

1 回答 1

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

请注意,我必须创建 field NON_FOCUSABLE,因为如果您通过paint()像这样更改字体来欺骗该字段,蓝色光标将与底层文本不匹配。您也可以通过覆盖drawFocus()和不执行任何操作来删除光标。

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

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

这是我的示例代码的输出:

在此处输入图像描述

于 2013-02-09T22:41:41.593 回答