Reinherd Reinherd - 19 days ago 11
Android Question

TextView with a background and Transparent Text

I'm trying to do the following:

enter image description here

For now, I am trying to use NativeAndroid.

However, I can do this with HTML and css.

As you can see, it's something like:


  • Holder with blue (might be any other color or even an IMAGE) background

  • TextView with (transparent??) color

  • TextView with gray background



However, if I set background to grey and the text to transparent, the text "disappears" and it's all shown as gray.

This is my try (Native Android):

<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="#ff000000" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ffcecece"
android:padding="5dp"
android:text="@string/hello_world"
android:textColor="#00ffffff" />
</RelativeLayout>


However, it's showing the following:

enter image description here

There's text, bu as it is transparent, it's not shown.

So my question is:


  • How can I achieve this?

  • Canvas? Spans? I'm not used to those approach, so some directions would be appreciated.



Thanks!!

Edit:
That blue background must be dynamic and it may be an IMAGE!

Answer

you can use Canvas for that:

Bitmap bmOverlay = Bitmap.createBitmap(1200, 1200, Bitmap.Config.ARGB_8888);//bMap.getConfig());

Canvas canvas = new Canvas(bmOverlay);
canvas.drawColor(Color.LTGRAY);
Paint paint = new Paint();

Paint mPaintText = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaintText.setStrokeWidth(3);
mPaintText.setStyle(Paint.Style.FILL_AND_STROKE);
mPaintText.setColor(Color.TRANSPARENT);
mPaintText.setTextSize(50f);
mPaintText.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));    
canvas.drawText("Your TExt", x, y, mPaintText);