2010-11-24 128 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; 
} 

享受:)