0

我有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(returnedBitmap);
    Drawable bgDrawable =view.getBackground();
    if (bgDrawable!=null) 
        bgDrawable.draw(canvas);
    else 
        canvas.drawColor(Color.WHITE);
    view.draw(canvas);
    return returnedBitmap;
    }
    else 
        return null;
}

然后我在 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,但得到了相同的结果。我可以使用什么解决方案?

4

1 回答 1

1

我已经这样解决了我的问题:

  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() 方法。

官方解释

于 2013-05-21T09:54:00.337 回答