2013-04-10 42 views
0

當我將TextView的DrawingCache繪製到另一個View的Canvas時,TextView的重力在垂直方向上沒有效果。TextViews重力不垂直工作

這裏的類繪製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內容的嚴重性只在水平方向生效。

什麼原因和如何解決這個問題,如果它的錯誤?

謝謝

回答

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); 


    } 

} 
+0

這將在中心繪製TextView的內容,但Size現在像「wrap_content」一樣。我想實現一個類,它使用邊框(頂部,左側,右側,底部或圓角)來裝飾每個視圖。所以這裏的這個類僅僅是用來演示沒有所有其他代碼的行爲的例子。我的班級用邊框作品來裝飾視圖,包括填充和邊距 - 但重力不是。 – steffka 2013-04-10 13:47:39

+0

你得到的位圖是完全相同的高度,你提供的內部佈局參數tv.setLayoutParams(新的LinearLayout.LayoutParams(300,200)); – Triode 2013-04-10 13:51:19

+0

哦,好的。我錯過了。非常感謝你! – steffka 2013-04-11 07:42:24