10

可能重复:
将视图转换为位图而不在 Android 中显示?

我正在尝试从以下参考链接将视图转换为位图

链接文本

现在的问题是我如何才能获得仅从视图转换的位图。在示例中作者使用了 relativelayout.dispatchDraw(c) 但这一行给了我编译时错误,即

ViewGroup 类型的方法 dispatchDraw(Canvas) 不可见

这是我的代码,我在 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

4

2 回答 2

28

这是我的解决方案:

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

享受 :)

于 2012-03-07T04:50:58.247 回答
6

这对我有用:

Bitmap viewCapture = null;

theViewYouWantToCapture.setDrawingCacheEnabled(true);

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

theViewYouWantToCapture.setDrawingCacheEnabled(false);

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

于 2011-02-01T02:01:46.610 回答