首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android RadioButton 圖片垂直居中:重寫 onDraw 計算文字高度與圖片偏移實現

     編輯:程式設計綜合問答

問題場景

RadioButton 設定 drawableTop 圖片,文字在下方,整體內容(圖片+間距+文字)需在控件高度中垂直居中。

核心實現:重寫 onDraw 平移畫布

public class CenteredRadioButton extends RadioButton {
    public CenteredRadioButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Drawable[] drawables = getCompoundDrawables();
        if (drawables != null) {
            Drawable drawableTop = drawables[1]; // TOP
            if (drawableTop != null) {
                // 1. 計算文字高度
                float textHeight = measureTextHeight(getText().toString());
                // 2. 獲取間距與圖片高度
                int drawablePadding = getCompoundDrawablePadding();
                int drawableHeight = drawableTop.getIntrinsicHeight();
                // 3. 總內容高度
                float contentHeight = textHeight + drawablePadding + drawableHeight;
                // 4. 設置頂部內邊距將內容推至垂直中心
                setPadding(0, (int)((getHeight() - contentHeight) / 2), 0, 0);
                // 5. 畫布平移微調(可選,視具體對齊效果)
                canvas.translate(0, -(getHeight() - contentHeight) / 2);
            }
        }
        super.onDraw(canvas);
    }

    private int measureTextHeight(String text) {
        Paint.FontMetrics fm = getPaint().getFontMetrics();
        return (int) (fm.descent - fm.ascent + fm.leading);
    }
}

XML 使用

<com.example.CenteredRadioButton
    android:layout_width="wrap_content"
    android:layout_height="80dp"  
    android:drawableTop="@drawable/ic_radio"
    android:drawablePadding="8dp"
    android:text="選項"
    android:gravity="center_horizontal" />

關鍵原理

  • setPadding(top):動態調整頂部內邊距,將複合內容(drawable+文字)整體下移
  • canvas.translate():繪製時進一步微調畫布原點,修正基線對齊偏差
  • FontMetrics:精確獲取文字繪製區域高度(含 descent/ascent/leading)

替代方案

  • LinearLayout 包裹 ImageView + TextView + RadioButton (隱藏按鈕),佈局層級控制居中
  • ConstraintLayout 指鏈約束實現視覺居中

RadioButton 複合可繪對象佈局由系統內部固定邏輯控制,想要精確居中必須介入繪製流程(onDraw)或改用組合佈局。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved