将视图转换为位图

Hun*_*unt 10 android bitmap android-canvas

可能重复:
将视图转换为位图而不在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);
Run Code Online (Sandbox Code Playgroud)

这里的returnedBitmap应该包含(ImageView和TextView)的图像,但是这个位图只包含relativeView的bacground位图,即bgblack

Gil*_* SH 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;
}
Run Code Online (Sandbox Code Playgroud)

请享用 :)


cot*_*aws 6

这对我有用:

Bitmap viewCapture = null;

theViewYouWantToCapture.setDrawingCacheEnabled(true);

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

theViewYouWantToCapture.setDrawingCacheEnabled(false);
Run Code Online (Sandbox Code Playgroud)

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