0

给定资源中的字符串,我怎样才能得到它的边界矩形?

对于纯文本,我可以使用 Paint.getTextBounds(),但这是来自资源的字符串,其中包含换行符和属性设置。

<string name="foobar"><small>Foo</small>\nBar</string>

换句话说,我正在实现一个自定义视图,它将显示这样的字符串,并且我想计算我的视图的大小。

更多细节:基本上,我正在实现 TextView 的一种变体,它调整其字体大小以适应可用空间,而不是调整其大小以适应文本。

4

2 回答 2

1

You want to show html in your custom view. Do i make it clear?

If you want to implements this all by your own code. It is a very huge work. Extending TextView and overriding some methods is the best choice, but if you insist on writing your own class, you can still get help from some system class.

Showing and measuing html should follow the code of TextView, you can find this in TextView.onDraw() and TextView.onMeasure(), here i just talk about the steps for measuring html.

  1. Parsing html. Use Html.fromHtml() to get a Spanned text.
  2. Create a StaticLayout or DynamicLayout with the spanned text.
  3. Use Layout.getLineWidth() and Layout.getHeight() to measure the text.
于 2012-12-18T06:32:35.430 回答
0

尝试这个 :

字符串.xml

       <string name="foobar"><small>Foo</small>\nBar</string>

活动中

       final TextView mytext = (TextView) findViewById(R.id.my_textView);
       mytext.setText(getString(R.string.foobar));

       Button btn_getTextBounds = (Button) findViewById(R.id.ok);
       btn_getTextBounds.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
               Rect rectf = new Rect();
               mytext.getLocalVisibleRect(rectf);

               Log.d("WIDTH        :",String.valueOf(rectf.width()));
               Log.d("HEIGHT       :",String.valueOf(rectf.height()));
               Log.d("left         :",String.valueOf(rectf.left));
               Log.d("right        :",String.valueOf(rectf.right));
               Log.d("top          :",String.valueOf(rectf.top));
               Log.d("bottom       :",String.valueOf(rectf.bottom));
           }
       });

它将在可见屏幕区域显示 TextView 使用的必需属性。

希望它可以帮助你。

谢谢。

于 2012-12-18T05:56:29.820 回答