带有背景和透明文本的TextView

6
我想要实现以下功能:
在原生Android中,我目前正在尝试使用。但是,我可以使用HTML和CSS来做到这一点。
如您所见,它看起来像这样:
- 具有蓝色(也可能是其他颜色或甚至是图像)背景的持有人 - 具有(透明??)颜色的文本视图 - 具有灰色背景的文本视图
然而,如果我将背景设置为灰色并将文本设置为透明,则文本会“消失”,并且所有内容都会显示为灰色。
以下是我的尝试(原生安卓):
<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>

然而,它显示了以下内容:
有文字,但由于是透明的,所以没有显示。
所以我的问题是:
如何实现这个?
Canvas?Spans?我不习惯这些方法,因此需要一些指导。
谢谢!!
编辑:
那个蓝色背景必须是动态的,它可以是一张图片!

1
你会使用动态背景吗?如果不会,就将文本颜色设置为背景颜色。 - Losiowaty
背景很可能是一张图片……所以它完全是动态的。 - Reinherd
我已经编辑了我的问题,请查看编辑注释。 - Reinherd
@Reinherd:您正在寻找我这个答案 - Gil Vegliach
@GilVegliach 我在三年前的时候还很年轻 :D - Reinherd
@Reinherd:你说得对:D 无论如何,这将是未来的一个很好的参考。 - Gil Vegliach
3个回答

3
您可以使用Canvas来实现这个功能:
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);

1
我不习惯使用画布。我该如何将此代码添加为视图? - Reinherd
您可以在布局中添加一个 ImageView,然后使用以下代码:ImageView image = (ImageView)getActivity().findViewById(R.id.imageView1);image.setImageBitmap(bmOverlay); - Dima
我已经尝试过了,如果文本是透明的,它就是不可见的,所以这并不起作用。 - Reinherd
尝试这个:http://android.okhelp.cz/create-bitmap-and-draw-text-into-bitmap-android-example/ - Dima
这正是我所需要的。然而,我尝试在我的应用程序中使用它(复制并粘贴),但文本不透明。你能试试吗? - Reinherd
1
好的,使用以下代码它可以正常工作: paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC)); - Reinherd

1
textcolor设置为您的布局backgound颜色,如浅天蓝色。

0

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

不是我需要的。请检查我的编辑。 - Reinherd
您可以在Java类中设置背景资源,方法如下:mRelativeLayout.setBackgroundResource(R.drawable.imagename); - jyomin
这不是关于图像的问题,而是关于将文本设置为透明,以便您可以“透过”TextView阅读。 - Reinherd
你不理解我想做什么。请再次检查问题。 - Reinherd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接