如何制作带有纹理的文本而不是文本颜色或渐变(例如 png 文件)?类似于 this .我理解逻辑,我应该使文本颜色透明并放在文本位图下。我认为我无法使用 Textview
实现此目的。而且我不知道如何使用 Canvas 或 OpenGL 来完成。有什么想法吗?
最佳答案
这是一种使用 PorterDuffXfermode
的方法。
public class MainActivity extends Activity {
private EditText mEditText;
private ImageView mImageView;
private Bitmap mTexture;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditText = (EditText) findViewById(R.id.activity_main_edittext);
mImageView = (ImageView) findViewById(R.id.activity_main_image);
mTexture = BitmapFactory.decodeResource(getResources(),
R.drawable.texture);
}
public void onTextCreate(View v) {
final String text = mEditText.getEditableText().toString();
Bitmap result = Bitmap.createBitmap(mTexture.getWidth(),
mTexture.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setTextSize(200);
paint.setARGB(255, 0, 0, 0);
canvas.drawText(text, 200, 200, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(mTexture, 0, 0, paint);
paint.setXfermode(null);
mImageView.setImageBitmap(result);
}
}
布局非常简单:
<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"
tools:context=".MainActivity">
<EditText
android:id="@+id/activity_main_edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:hint="Write a sample text" />
<ImageView
android:id="@+id/activity_main_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:onClick="onTextCreate"
android:text="Do it!" />
</RelativeLayout>
此代码使用 canvas.drawText()
编写文本。如果您想使用常规的 TextView
,您可以:
- 创建
TextView
- 设置文本
- 使用
textView.draw(canvas); 将
TextView
绘制到 Canvas 中; - 不要使用
canvas.drawText()
使用canvas.drawBitmap()
关于安卓带纹理的文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14791012/