我将ImageButton子类化,以便在其上绘制线条,并试图弄清楚实际按钮坐标在我的gridview中的位置。我正在使用onGlobalLayout来设置“上”,“下”,“右”和“左”,但是这些似乎是针对网格内的实际“正方形”,而不是实际的按钮(参见图片)。紫线是使用从myImageButton.onGlobalLayout()收集的坐标在myImageButton.onDraw()中绘制的。我以为这些是用于按钮的,但它们似乎来自其他方面。不知道是什么。我希望紫色线条与按钮的轮廓匹配,以便我绘制的线条出现在按钮上,而不仅仅是在LinearLayout中的某个地方浮动。浅蓝色是包含Textview(用于数字)和myImageButton的垂直LinearLayout的背景颜色。有没有办法得到实际的按钮尺寸?
XML布局:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/lay_cellframe"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="fill_vertical|fill_horizontal"
android:orientation="vertical" >
<TextView
android:id="@+id/tv_cell"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:gravity="center"
android:text="TextView"
android:textSize="10sp" />
<com.example.icaltest2.myImageButton
android:id="@+id/imageButton1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:layout_margin="0dp"
android:adjustViewBounds="false"
android:background="@android:drawable/btn_default"
android:scaleType="fitXY"
android:src="@android:color/transparent" />
</LinearLayout>
</FrameLayout>
myImageButton.java
public myImageButton (Context context, AttributeSet attrs)
{
super (context, attrs);
mBounds = new Rect();
ViewTreeObserver vto = this.getViewTreeObserver ();
vto.addOnGlobalLayoutListener (ogl);
Log.d (TAG, "myImageButton");
}
...
OnGlobalLayoutListener ogl = new OnGlobalLayoutListener()
{
@Override
public void onGlobalLayout ()
{
Rect b = getDrawable ().getBounds ();
mBtnTop = b.centerY () - (b.height () / 2);
mBtnBot = b.centerY () + (b.height () / 2);
mBtnLeft = b.centerX () - (b.width () / 2);
mBtnRight = b.centerX () + (b.width () / 2);
}
};
...
@Override
protected void onDraw (Canvas canvas)
{
super.onDraw (canvas);
Paint p = new Paint ();
p.setStyle (Paint.Style.STROKE);
p.setStrokeWidth (1);
p.setColor (Color.MAGENTA);
canvas.drawCircle (mBtnLeft, mBtnTop, 2, p);
canvas.drawCircle (mBtnLeft, mBtnBot, 2, p);
canvas.drawCircle (mBtnRight, mBtnTop, 2, p);
canvas.drawCircle (mBtnRight, mBtnBot, 2, p);
canvas.drawRect (mBtnLeft, mBtnTop, mBtnRight, mBtnBot, p);
}
更新:添加了具有史密斯的建议的图像
Rect r = canvas.getClipBounds (); //<- not sure about this
int w = getMeasuredWidth () - getPaddingLeft () - getPaddingRight ();
int h = getMeasuredHeight () - getPaddingTop () - getPaddingBottom ();
int left = r.centerX () - (w / 2);
int right = r.centerX() + ( w / 2);
int top = r.centerY() - (h / 2);
int bot = r.centerY() + (h / 2);
p.setColor (Color.GREEN);
canvas.drawRect (left, top, right, bot, p);
最佳答案
在调用onDraw时,已处理布局,并且尺寸信息应该可用。您可以使用View.getMeasuredWidth() / View.getMeasuredHeight()
检索所需的信息。但是,您可能还需要考虑View.getPaddingLeft() / ..
的填充。例如:
final int displayWidth = (getMeasuredWidth() - getPaddingLeft() - getPaddingRight());