2012-09-13 65 views
2

我有一個觀點是從佈局膨脹:如何將充氣的視圖轉換爲位圖?

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View tagView = inflater.inflate(R.layout.activity_main, null); 
TextView name = (TextView) tagView.findViewById(R.id.textView1); 
name.setText("hello"); 

現在我想隱蔽充氣視圖爲位圖

我應該怎麼辦?

回答

6

你可以把它按以下步驟進行:

//first, View preparation 
LayoutInflater inflater = 
    (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View tagView = inflater.inflate(R.layout.activity_main, null); 
TextView name = (TextView) tagView.findViewById(R.id.textView1); 
name.setText("hello"); 


//second, set the width and height of inflated view 
tagView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 
    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); 
tagView.layout(0, 0, tagView.getMeasuredWidth(), tagView.getMeasuredHeight()); 


//third, finally conversion 
final Bitmap bitmap = Bitmap.createBitmap(tagView.getMeasuredWidth(), 
tagView.getMeasuredHeight(), Bitmap.Config.ARGB_8888); 
Canvas canvas = new Canvas(bitmap); 
tagView.draw(canvas); 

最後,你有你的充氣tagViewbitmap

+0

崩潰的原因tagView.getLayoutParams()。width和tagView.getLayoutParams()。高度返回NullPointerException異常 – user1531240

+1

看到我的更新答案...它工作正常:) – waqaslam

+0

tagView.measure(MeasureSpec.makeMeasureSpec(0,MeasureSpec.UNSPECIFIED ), MeasureSpec.makeMeasureSpec(0,MeasureSpec.UNSPECIFIED)); 將拋出NullPointExcetion – user1531240