根据主题“将 TextView 截图为位图”可以找到很多帖子。
嗯,与我的问题不同的是,首先将视图绘制在显示器上(所有布局和测量工作都已完成),然后绘制到连接到位图的画布中。
我只想从头开始创建一个 TextView,而不显示在渲染为位图的显示器上。
这是已经运行的基本配置。单击 TextView 会将其自身绘制为 Bitmap 并将其设置为 ImageView。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical" android:background="#fff">
<TextView android:id="@+id/tv" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="The Quick Brown Fox Jumps Over The Lazy Dog."
android:textSize="20dip" android:background="#abcdef"
android:textColor="#000" android:padding="10dip"
android:layout_margin="10dip" />
<ImageView android:id="@+id/iv" android:layout_width="449px"
android:layout_height="47px" android:background="#56789a"
android:layout_margin="10dip" />
</LinearLayout>
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.tv).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Bitmap bmp = Bitmap.createBitmap(449, 47, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
v.draw(canvas);
ImageView iv = (ImageView) findViewById(R.id.iv);
iv.setImageBitmap(bmp);
}
});
}
现在是有问题的部分。我将在 Java 中创建一个 TextView,并且希望将其直接绘制到位图中。之后我将其设置为 ImageView。我从来没有运行过这个:(
Bitmap bmp = Bitmap.createBitmap(449, 47, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
TextView tv = new TextView(this);
tv.setText("THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG");
tv.setTextSize(55f);
tv.setTextColor(this.getResources().getColor(android.R.color.black));
tv.draw(canvas);
ImageView iv = (ImageView) findViewById(R.id.iv);
iv.setImageBitmap(bmp);
这在 onCreate 和 OnClickListener 中都不起作用。尝试 setDrawingCacheEnabled()、measure() 和 requestLayout() 也不起作用。