当我将TextView的DrawingCache绘制到另一个View的Canvas时,TextView的重力在垂直方向上没有效果。
这里的类将TextViews画布绘制为自己的画布:
public class GravityDecorator extends View{
private View view;
private Paint paint= new Paint();
public GravityDecorator(View view,Context context) {
super(context);
this.view = view;
view.setDrawingCacheEnabled(true);
view.layout(0, 0,600,500);
this.layout(0, 0,600,500);
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
view.buildDrawingCache();
canvas.drawBitmap(view.getDrawingCache(), 0, 0, paint);
view.destroyDrawingCache();
}
}
以下是测试它的代码(onCreate):
ViewGroup root = (ViewGroup) findViewById(R.id.root); // is a linear_layout - width and height is match_parent
TextView tv = new TextView(getApplicationContext());
tv.setText("Hello World!");
tv.setTextSize(40.0f);
tv.setLayoutParams(new LinearLayout.LayoutParams(300,200));
tv.setTextColor(Color.WHITE);
tv.setBackgroundColor(Color.parseColor("#3131c5"));
tv.setGravity(Gravity.CENTER);
GravityDecorator gd = new GravityDecorator(tv, getApplicationContext());
root.addView(gd);
如您所见,TextViews内容的重力仅在水平方向生效。
如果是一个错误,是什么原因以及如何解决这个问题?
谢谢
答案 0 :(得分:1)
root = (ViewGroup) findViewById(R.id.root); // is a linear_layout - width and height is match_parent
tv = new TextView(getApplicationContext());
tv.setText("Hello World!");
tv.setTextSize(40.0f);
tv.setLayoutParams(new LinearLayout.LayoutParams(300,200));
tv.setTextColor(Color.WHITE);
tv.setBackgroundColor(Color.parseColor("#3131c5"));
tv.setGravity(Gravity.CENTER);
tv.invalidate();
root.addView(tv);
GravityDecorator gd = new GravityDecorator(tv, getApplicationContext());
root.addView(gd);
可能是因为最初没有为TextView
设置布局参数。尝试将视图添加到Parent,然后获取drawingCache
。
public class GravityDecorator extends View{
private View view;
private Paint paint= new Paint();
public GravityDecorator(View view,Context context) {
super(context);
this.view = view;
view.setDrawingCacheEnabled(true);
view.layout(0, 0,600,500);
this.layout(0, 0,600,500);
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
canvas.drawBitmap(bmp, 0, 0, paint);
view.destroyDrawingCache();
if(root.indexOfChild(tv) != -1)
root.removeView(tv);
}
}