将视图转换为位图 [英] convert view into bitmap
问题描述
可能的重复:
将视图转换为位图而不在 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(Canvas)方法来自类型 ViewGroup 不可见
The method dispatchDraw(Canvas) from the type ViewGroup is not visible
这是我的代码,我在 onCreate 函数中编写了以下代码
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);
这里返回的Bitmap应该包含(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;
}
享受:)
这篇关于将视图转换为位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!