我的目的是制作一个Bitmap
显示用户提供的文本的图像,然后可以将图像保存到缓存中。
调用 TextView.setText()
and后TextView.invalidate()
,TextView
并没有像我预期的那样更新。它仍然在Canvas
.
@Override
public void onClick(View v) {
// tv is a TextView and et is an EditText.
tv.setText(et.getText().toString());
tv.invalidate();
// if measure() isn't called, getMeasuredWidth() returns previous value.tv.measure(0, 0);
int screenWidth = (int) tv.getMeasuredWidth();
int screenHeight = (int) tv.getMeasuredHeight();
if (screenHeight * screenWidth != 0) {
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
screenWidth, screenHeight);
Bitmap testB;
testB = Bitmap.createBitmap(screenWidth, screenHeight, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(testB);
tv.draw(c);
// tv draws previous String on Canvas c.
iv = (ImageView) findViewById(R.id.image);
iv.setLayoutParams(layoutParams);
iv.setBackgroundColor(Color.RED);
iv.setImageBitmap(testB);
}
}
文件说
public void invalidate ()
使整个视图无效。如果视图可见,
onDraw(android.graphics.Canvas)
将在将来的某个时间点调用。这必须从 UI 线程调用。要从非 UI 线程调用,请调用postInvalidate()
.
这是否意味着我应该重写该onDraw()
方法?