将视图转换为位图

时间:2010-11-24 09:03:06

标签: android bitmap android-canvas

  

可能重复:
  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)的图像,但是这个位图只包含relativeView的bacground位图,即bgblack

2 个答案:

答案 0 :(得分:27)

这是我的解决方案:

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

享受:)

答案 1 :(得分:6)

这对我有用:

Bitmap viewCapture = null;

theViewYouWantToCapture.setDrawingCacheEnabled(true);

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

theViewYouWantToCapture.setDrawingCacheEnabled(false);

我认为视图必须是可见的(即getVisiblity()== View.VISIBLE)。如果您尝试捕获它但同时将其隐藏给用户,则可以将其移出屏幕或将其放在屏幕上。