Android 将从RelativeLayout创建的位图设置为imageView
我有RelativeLayout,我想将其转换为位图,如下所示:Android 将从RelativeLayout创建的位图设置为imageView,android,bitmap,android-relativelayout,android-imageview,dynamic-data,Android,Bitmap,Android Relativelayout,Android Imageview,Dynamic Data,我有RelativeLayout,我想将其转换为位图,如下所示: public static Bitmap getBitmapFromView(View view) { if (view != null) { Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(re
public static Bitmap getBitmapFromView(View view) {
if (view != null)
{ 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;
}
else
return null;
}
public Bitmap getBitmapFromView() {
this.measure(MeasureSpec.makeMeasureSpec(createNewRelativeLayoutParams().width, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(createNewRelativeLayoutParams().height, MeasureSpec.UNSPECIFIED));
this.layout(0, 0, this.getMeasuredWidth(), this.getMeasuredHeight());
Bitmap returnedBitmap = Bitmap.createBitmap(this.getMeasuredWidth(), this.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(returnedBitmap);
this.draw(c);
return returnedBitmap;
}
然后我在onCreate()方法中动态创建RelativeLayout cView,并将其设置为ImageView,如下所示:
dialer = (ImageView) findViewById(R.id.imageView_ring);
dialer.setImageBitmap(getBitmapFromView(cView));
和获取错误:
05-20 13:48:27.509: E/AndroidRuntime(28367):
java.lang.RuntimeException: Unable to start activity
ComponentInfo{ru.biovamp.widget/ru.biovamp.widget.TestCircleAct}:
java.lang.IllegalArgumentException: width and height must be > 0
我还尝试通过onStart()方法将位图添加到ImageView中,但得到了相同的结果。我可以使用什么解决方案?我已经这样解决了我的问题:
public static Bitmap getBitmapFromView(View view) {
if (view != null)
{ 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;
}
else
return null;
}
public Bitmap getBitmapFromView() {
this.measure(MeasureSpec.makeMeasureSpec(createNewRelativeLayoutParams().width, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(createNewRelativeLayoutParams().height, MeasureSpec.UNSPECIFIED));
this.layout(0, 0, this.getMeasuredWidth(), this.getMeasuredHeight());
Bitmap returnedBitmap = Bitmap.createBitmap(this.getMeasuredWidth(), this.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(returnedBitmap);
this.draw(c);
return returnedBitmap;
}
所以解决方案是,我们应该在绘制它之前调用measure()和layout()方法
我想说的是,输出位图看起来应该是这样的。我想问题出在measure()方法中。仍在寻找解决方案。