转换视图为位图位图、视图

2023-09-12 09:28:35 作者:不做畜女好多年

可能重复:   Converting为了不位图在Android中显示出来?

我想认为从以下参考链接

I am trying to convert the view into bitmap from following reference link

链接文本

现在的问题是我怎么能得到正从只查看转换位图。在这个例子中笔者使用relativelayout.dispatchDraw(C),但此行是给我编译时错误即

Now the problem is how can i get the bitmap that is being converted from view only. in the example author has used relativelayout.dispatchDraw(c) but this line is giving me compile time error i.e.

该从方法dispatchDraw(画布)   类型的ViewGroup不可见

The method dispatchDraw(Canvas) from the type ViewGroup is not visible

下面是我的code和我写的onCreate函数中以下code

Here is my code and i have written the following code inside onCreate function

    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

Here the returnedBitmap should contain the image of (ImageView and TextView) but this bitmap contains only bacground bitmap of relativeView i.e. bgblack

推荐答案

这里是我的解决方案:

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

享受:)