我正在继承 ImageButton 以便在其上绘制线条并试图找出实际按钮坐标在我的 gridview 中的位置。我正在使用 onGlobalLayout 来设置顶部、底部、右侧和左侧,但这些似乎是针对网格内的实际“正方形”,而不是实际按钮(见图)。紫色线是使用从 myImageButton.onGlobalLayout() 收集的坐标在 myImageButton.onDraw() 中绘制的。我认为这些将用于按钮,但它们似乎来自其他东西。不确定是什么。我希望紫色线条与按钮的轮廓相匹配,这样我绘制的线条就会出现在按钮上,而不仅仅是漂浮在某个地方的 LinearLayout 中。浅蓝色是垂直 LinearLayout 的背景颜色,它包含 Textview(用于数字)和 myImageButton。有什么办法可以得到实际的按钮大小?
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);
}
更新:添加了 jsmith 建议的图片
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);