我试图跟踪一个类扩展LinearLayout
内的子TextView
的边界Rect
,我使用View.getGlobalVisibleRect(Rect)
以获得TextView的边界框相对于它的父。它在某些设备上运行良好,但在其他手机上显然存在某种单元问题。我看到的一个简单的例子:
//Extended LinearLayout's onDraw
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
TextView tv = (TextView)findViewById(R.id.textView1);
Rect bounds = new Rect();
tv.getGlobalVisibleRect(bounds);
canvas.drawRect(bounds, myPaint);
}
期望的是它应该在textviewtv下画一个框。在我的3.1版本的平板电脑上是这样的,但在我的1.6和2.3版本的手机上,它会在TextView下面画一个框。似乎我需要将边界框的值转换为不同类型的像素单位,以便始终如一地获得预期的结果。
问题是我不确定返回的矩形是否已经在DIP或标准像素中。我两个都试过了:
bounds.top = TypedValue.complexToDimensionPixelSize(bounds.top, getContext().getResources().getDisplayMetrics());
和
bounds.top = TypedValue.COMPLEX_UNIT_DIP, bounds.top, getContext().getResources().getDisplayMetrics());
但是这两个似乎都没有将盒子顶部转换到它应该在的地方。我将非常感谢任何反馈或建议。
谢谢!
事实证明,getGlobalVisibleRect
要么在3.0之前被打破,要么不返回我所期望的。我发现我可以这样做。
TextView tv = (TextView)findViewById(R.id.textView1);
Rect bounds = new Rect(tv.getLeft(), tv.getTop(), tv.getRight(), tv.getBottom());