【问题标题】:Different font size in same field同一字段中的不同字体大小
【发布时间】:2013-02-09 16:45:14
【问题描述】:

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

【问题讨论】:

    标签: blackberry user-interface java-me paint


    【解决方案1】:

    如果您真的想通过更改被覆盖的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 &lt;span&gt; 标签),那么RichTextField 可能是最好的选择。

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

    【讨论】:

      猜你喜欢
      • 2013-04-26
      • 1970-01-01
      • 1970-01-01
      • 2014-01-29
      • 1970-01-01
      • 2013-01-16
      • 2015-03-20
      • 1970-01-01
      • 2014-02-13
      相关资源
      最近更新 更多