带有背景颜色和透明文字的按钮

23
我有一个带有背景图片的布局,并在其上放置了一个按钮。按钮的背景颜色是白色。现在我想以一种方式编写文本,使文本通过它显示按钮后面的任何内容(如透明文本)。显然,如果我将文本颜色设置为透明,则文本将消失,我将看到一个没有文本的白色按钮。如何做到这一点? 截图: button with transparent text

你可以使用TextView并给它一个背景图片。TextView与按钮一样可点击。默认情况下,它们的背景是透明的。因此,只需准备一个带有雕刻文本的png图像(好的,每个分辨率都需要一个),然后就完成了。 - Phantômaxx
1
@DerGolem 显然,如果我有一张带有透明文本的png图像,它会起作用。但我想不使用任何图像来完成它。假设我的应用程序中有50-60甚至更多的按钮。我不能拥有那么多的图像。因此,我需要一个更好的解决方案。 - berserk
作为一种替代方案,您可以创建一个自定义控件来扩展视图,并在onDraw方法中从背景填充中切除文本。 - Phantômaxx
我真的不确定。我知道你可以在TextViews中使用基本的HTML和一些CSS,但我不知道支持到什么程度。你可能可以整合一个WebView并使用一些基本的PHP或其他东西来显示资产文件夹中使用HTML和CSS提供的文本。再次强调,这只是我随意提出的想法,我不确定是否可行。 - indivisible
@indivisible 我认为你提到的不可能实现,即使可以实现,也不是高效的,并且存在缺陷。这不仅仅涉及布局的背景。如果按钮后面有其他视图,文本也必须将它们显示出来。 - berserk
显示剩余4条评论
1个回答

26

两种方法:(1)不是很精确的解决方案,因为文本对齐应该由手动编码实现,但是:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button view1 = new Button(this);

    RelativeLayout layout1 = (RelativeLayout) findViewById(R.id.layout1);
    layout1.setBackground(getResources().getDrawable(R.drawable.choose_background));

    layout1.addView(view1);

    Bitmap mainImage = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);
    {
        //creating image is not necessary, more important is ability to grab the bitmap.
        Canvas canvas = new Canvas(mainImage);
        canvas.drawColor(Color.WHITE);
        view1.setBackground(new BitmapDrawable(getResources(), mainImage));
    }

    {
        Canvas canvas = new Canvas(mainImage);
        //most interesting part:
        Paint eraserPaint = new Paint();
        eraserPaint.setAlpha(0); //this
        eraserPaint.setTextSize(200);
        eraserPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN)); //and this
        canvas.drawText("some", 10, 150, eraserPaint);
    }
}

eraserPaint的想法来自于这里使用PorterDuff模式擦除位图部分和这里Android如何在ImageView上应用蒙版?

在activity_main.xml中一切都是默认的:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/layout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.runup.myapplication2.app.MainActivity">

结果如下:

enter image description here

(2) 第二种方法是将此行为添加到类中,以便在xml中使用。 https://github.com/togramago/ClearTextViewProject - 这是一个带有示例的库项目。您可以将其作为库添加或仅复制ClearTextView类到您的项目中(因为它是没有xml资源的扩展TextView)。能够适应配置更改和动态文本和/或背景更改。

纵向模式下的示例结果:enter image description here

横向模式下的示例结果:enter image description here


+1 做得很好!但我想要一个自定义视图,可以在xml中使用。你能用它制作一个自定义视图吗? - berserk
将此内容作为类添加到您的项目中,并在xml中像普通TextView一样使用。尽管在尝试动态更改时可能会出现一些问题-但这只是一个建议。 - Margarita Litkevych
谢谢,我会尝试使用它! - berserk

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