1
我對Android非常陌生,正在尋找一些幫助將視圖轉換爲Bitmap
圖像。 我有一個Activity
,我創建了一個RelativeLayout
,並在頂部添加了2個TextViews
,一個在底部。如果顯示RelativeLayout
本身,則Activity
顯示正常。 我試圖將此視圖轉換爲Bitmap
並顯示爲ImageView
(添加到LinearLayout
)而不是顯示RelativeLayout
。但是顯示器似乎並沒有保留View
的佈局,而是將元素組合在一起並顯示在圖像中。在Android中將視圖轉換爲位圖圖像
有人能提出一些問題嗎? 下面是簡單的代碼我已經寫
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
LinearLayout finalImage = new LinearLayout(this);
finalImage.setLayoutParams(lp);
RelativeLayout main = new RelativeLayout(this);
main.setLayoutParams(lp);
TextView tv = new TextView(this);
tv.setTextColor(Color.RED);
tv.setText("Top Text Content");
tv.setGravity(Gravity.CENTER);
tv.setId(1);
lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
main.addView(tv,lp);
TextView headingView = new TextView(this);
headingView.setTextColor(Color.RED);
headingView.setPadding(15, 10, 10, 10);
headingView.setTextSize(20);
headingView.setText("Bottom Text Content");
headingView.setGravity(Gravity.CENTER);
headingView.setId(2);
lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
main.addView(headingView,lp);
main.setDrawingCacheEnabled(true);
// this is the important code :)
// Without it the view will have a dimension of 0,0 and the bitmap will be null
main.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
main.layout(0, 0, main.getMeasuredWidth(), main.getMeasuredHeight());
main.buildDrawingCache(true);
Bitmap returnedBitmap = Bitmap.createBitmap(main.getDrawingCache());
main.setDrawingCacheEnabled(false); // clear drawing cache
ImageView iv = new ImageView(this);
iv.setImageBitmap(returnedBitmap);
finalImage.addView(iv);
//setContentView(main);
setContentView(finalImage);
}