onDraw on View扩展了ImageButton不起作用

时间:2016-09-07 02:15:23

标签: android android-canvas android-custom-view ondraw android-imagebutton

我正在尝试在ImageButton上绘制自定义文本。我已经覆盖了onDraw(Canvas)方法,但它没有用。这是代码:

public class CustomImageButton extends ImageButton {

    private static final String TAG = "CustomImageButton";

    private String text = "";
    private float textSize;
    private int textColor;
    private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    public CustomImageButton(Context context) {
        super(context);
        initialize(null);
    }

    public CustomImageButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize(attrs);
    }

    public CustomImageButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialize(attrs);
    }

    private void initialize(AttributeSet attrs) {

        if (attrs != null) {
            TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.CustomImageButton);

            text = a.getString(R.styleable.CustomImageButton_text);
            textSize = a.getDimension(R.styleable.CustomImageButton_textSize, 20);
            textColor = a.getColor(R.styleable.CustomImageButton_textColor, getResources().getColor(R.color.white));
             //setBackgroundColor(getResources().getColor(R.color.transparent));
            a.recycle();
            invalidate();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Typeface font = Typefaces.get(getContext(), "fonts/my-font.ttf");
        paint.setColor(Color.WHITE);
        paint.setTypeface(font);
        paint.setTextSize(100);
        paint.setTextAlign(Paint.Align.CENTER);


        int xPos = canvas.getWidth() / 2;
        int yPos = (int) ((canvas.getHeight() / 2) - ((paint.descent() + paint.ascent()) / 2));
        canvas.drawText(text, xPos, yPos, paint);
    }
}

和XML布局:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#OOOOOO"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <com.my.app.CustomImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        app:text="Hello!"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"/>
 . . .

</RelativeLayout>

我使用了setWillNotDraw(false),但似乎无效。我已经确认我的自定义视图有一些正确的尺寸。

0 个答案:

没有答案