0

当我将 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 内容的 Gravity 仅在水平方向生效。

如果它是一个错误,是什么原因以及如何解决这个问题?

谢谢

4

1 回答 1

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最初没有设置布局参数。尝试将视图添加到父级,然后获取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);


    }

}
于 2013-04-10T13:42:57.970 回答