Masking properties for Textview in android

3.2k views Asked by At

I have a scrollView in my Activity,the background of scrollView is of multiple colours.

<ScrollView ---------->
  <RelativeLayout -------------/>
</ScrollView>

To my RelativeLayout I have added Views dynamically.

inflated xml:

<RelativeLayout --------------android:background="some transparent image">
  <TextView --------- ---------/>
</RelativeLayout>

I want my Text coloured to be same as Background colour. I have tried for the solution in many ways but could not succeed.

In iOS for achieving this they have used RSMaskedLabel (third party class), but I didn’t find anything similar to this in Android.

Still I didnt find any solution,can anyone help me please. I tried by using Bitmaps and Canvas but didnt worked for me.

enter image description here

1

There are 1 answers

9
Niko On BEST ANSWER

Some guidelines how to achieve this with custom TextView:

  1. Extend TextView component
  2. Create Bitmap and Canvas where you draw background and text
  3. Draw wanted background color into allocated Canvas(e.g. Color.argb(80, 255, 255, 255))
  4. Draw the text with Paint having mode PorterDuffXfermode(Mode.CLEAR) (Remember: Only allocate Bitmap and Canvas once) since you draw it into Bitmap
  5. Draw the Bitmap into TextViews canvas

Here is some sample code to get started with:

public class TransparentTextView extends TextView {

    private Paint mTextPaint;
    private Bitmap mBitmapToDraw;

    public TransparentTextView(Context context) {
        super(context);

        setup();
    }

    public TransparentTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

        setup();
    }

    public TransparentTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        setup();
    }

    private void setup() {
        mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mTextPaint.setTextSize(getTextSize());
        mTextPaint.setStyle(Paint.Style.FILL);
        mTextPaint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (mBitmapToDraw == null) {
            mBitmapToDraw = Bitmap.createBitmap(getWidth(), getHeight(),
                    Bitmap.Config.ARGB_8888);

            if (mBitmapToDraw != null) {
                Canvas c = new Canvas(mBitmapToDraw);

                c.drawColor(Color.argb(80, 255, 255, 255));

                c.drawText(getText().toString(), getPaddingLeft(),
                        getPaddingTop(), mTextPaint);
            }
        }

        if (mBitmapToDraw != null) {
            canvas.drawBitmap(mBitmapToDraw, 0, 0, null);
        } else {
            super.onDraw(canvas);
        }
    }
}

If you are setting text dynamically, you will need to reset mBitmapToDraw in order to get it refreshed.