drawRect unit issues android

佐手、 提交于 2019-12-11 01:01:22

问题


I am trying to keep track of the bounding Rect for a child TextView inside of a class extending LinearLayout I am using View.getGlobalVisibleRect(Rect) in order to get the TextView's bounding box relative to its parent. It works great on some devices, but there is obviously some kind of unit issue going on on other phones. Simple example of what I'm seeing:

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

Whats expected is that it should draw a box under the the TextView tv. It does on my 3.1 tablet, but on my 1.6 and 2.3 phones it draw the box underneath of the TextView. It seems that I need to convert the values of the bounding box to a differnt kind of pixel unit in order to get the results I expect consistently.

Problem is I am not sure if the Rect returned is already in DIP or standard pixels. I have tried doing both:

bounds.top = TypedValue.complexToDimensionPixelSize(bounds.top, getContext().getResources().getDisplayMetrics());

and

bounds.top = TypedValue.COMPLEX_UNIT_DIP, bounds.top, getContext().getResources().getDisplayMetrics());

But neither of these seems to be converting the box top to where it should be. I would greatly appreciate any feedback or advice.

Thanks!


回答1:


Turns out that getGlobalVisibleRect is either broken pre-3.0 or doesn't return what I am expecting. I found that I could do this instead.

TextView tv = (TextView)findViewById(R.id.textView1);
Rect bounds = new Rect(tv.getLeft(), tv.getTop(), tv.getRight(), tv.getBottom()); 


来源:https://stackoverflow.com/questions/6922074/drawrect-unit-issues-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!