我有一些背景图片的布局,上面有一个按钮。按钮的背景颜色是白色。现在我想在其上写一个文本,使文本显示按钮后面的任何内容(如透明文本)。现在,显然,如果我使文本颜色透明,文本将消失,我将看到一个没有文本的白色按钮。怎么做?
截图:
答案 0 :(得分:25)
两种方式:(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的想法来自Erase bitmap parts using PorterDuff mode和Android how to apply mask on 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">
结果是:
(2)第二种方法是将此行为添加到类中以便在xml中使用它。 https://github.com/togramago/ClearTextViewProject - 带有样本的图书馆项目。您可以添加为库或仅将ClearTextView类复制到项目中(因为它是没有xml资源的扩展TextView)。适用于配置更改和动态文本和/或背景更改。
纵向样本的结果:
and landscape: