How to put text in a drawable?

Viewed 74932

I'm trying to create a drawable on the fly to use as a background for a custom linearlayout. It needs to have hash marks and such (no big deal), but also have numbers labeling what the hash marks are (like a ruler). I know I can just create text elements and put them inside the linearlayout and just have the hash marks in the drawable, but I'm hoping to have them inside the drawable as well, so I don't have to do measurement calculations twice.

5 Answers

To answer the comments above regarding how to center the text:

mPaint.textAlign = Align.CENTER
...
// Centering for mixed case letters
canvas.drawText(mText, 0, mText.length,
        bounds.centerX().toFloat(), bounds.centerY().toFloat() - ((mPaint.descent() + mPaint.ascent()) / 2), mPaint)

// Centering for all uppercase letters
canvas.drawText(mText, 0, mText.length,
            bounds.centerX().toFloat(), bounds.centerY().toFloat() - mPaint.ascent() / 2, mPaint)

This allows you to put any View in a Drawable, including a TextView. You can even use styles in your XML layout.

public class ViewDrawable extends Drawable {
    final View mView;

    public ViewDrawable(final Context context, final @LayoutRes int layoutId) {
        this(LayoutInflater.from(context).inflate(layoutId, null));
    }

    public ViewDrawable(final @NonNull View view) {
        mView = view;
    }

    public View getView() {
        return mView;
    }

    @Override
    public void setBounds(int left, int top, int right, int bottom) {
        super.setBounds(left, top, right, bottom);
        final int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(right - left, View.MeasureSpec.EXACTLY);
        final int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(bottom - top, View.MeasureSpec.EXACTLY);
        mView.measure(widthMeasureSpec, heightMeasureSpec);
        mView.layout(left, top, right, bottom);
    }

    @Override
    public void draw(@NonNull Canvas canvas) {
        mView.draw(canvas);
    }

    @Override
    public void setAlpha(int alpha) {
        mView.setAlpha(alpha/255f);
    }

    @Override
    public void setColorFilter(@Nullable ColorFilter colorFilter) {

    }

    @Override
    public int getOpacity() {
        return PixelFormat.UNKNOWN;
    }
}
Related