2010-11-24 129 views
9

可能重複:
Converting a view to Bitmap without displaying it in Android?轉換視圖爲位圖

我想視圖轉換成位圖,從下面的參考鏈接

link text

現在的問題是我如何得到正在轉換的位圖 只讀。在該示例中作者已經使用relativelayout.dispatchDraw(c)中,但此行是給我編譯時間錯誤即

在這裏所述的方法dispatchDraw(Canvas)的從 類型的ViewGroup是不可見的是我的代碼,我已經寫的onCreate函數中下面的代碼

Canvas c=null; 

    //Create Layout 
    RelativeLayout relativeView ;   
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
    RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT 
    ); 

    relativeView = new RelativeLayout(this);    
    relativeView.setLayoutParams(lp); 

    //Background of Layout 
    Bitmap viewBgrnd = BitmapFactory.decodeResource(getResources(),R.drawable.bgblack); 
    relativeView.setBackgroundDrawable(new BitmapDrawable(viewBgrnd)); 

    //associated with canvas 
    Bitmap returnedBitmap =    Bitmap.createBitmap(320,480,Bitmap.Config.ARGB_8888);  
    c = new Canvas(returnedBitmap); 
    Paint paint = new Paint(); 


    //Create Imageview that holds image    
    ImageView newImage = new ImageView(this); 
    Bitmap srcBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.bgpink); 
    newImage.setImageBitmap(srcBitmap); 

    TextView newText = new TextView(this); 

    newText.setText("This is the text that its going to appear");  

    c.drawBitmap(viewBgrnd, 0, 0, paint); 
      relativeView.layout(100, 0, 256, 256); 
    relativeView.addView(newImage); 
    relativeView.addView(newText); 


     // here i am getting compile time error so for timing i have replaced this line 
     // with relativeView.draw(c); 

    relativeView.dispatchDraw(c); 

這裏returnedBitmap應該包含(ImageView的和的TextView)的圖像,但此位圖只包含relati的bacground位圖veView即bgblack

+1

我有同樣的問題前幾次,發現無解了。有人告訴我,繪圖緩存可以是一個點。但是我無法以正確的方式工作。 – Impression 2010-11-24 09:12:01

+0

我不知道如何使用draw cache – Hunt 2010-11-24 09:22:33

回答

6

這個工作對我來說:

Bitmap viewCapture = null; 

theViewYouWantToCapture.setDrawingCacheEnabled(true); 

viewCapture = Bitmap.createBitmap(theViewYouWantToCapture.getDrawingCache()); 

theViewYouWantToCapture.setDrawingCacheEnabled(false); 

我相信視圖具有可見(即。 getVisiblity()== View.VISIBLE)。如果您試圖捕捉它,但同時將其隱藏給用戶,則可以將其從屏幕上移開或將其放在屏幕上。

25

這裏是我的解決方案:

public static Bitmap getBitmapFromView(View view) { 
    Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888); 
    Canvas canvas = new Canvas(returnedBitmap); 
    Drawable bgDrawable =view.getBackground(); 
    if (bgDrawable!=null) 
     bgDrawable.draw(canvas); 
    else 
     canvas.drawColor(Color.WHITE); 
    view.draw(canvas); 
    return returnedBitmap; 
} 

享受:)