Android:生成视图的位图而不绘图

时间:2013-05-16 22:11:30

标签: android android-canvas

我们从特定视图生成位图时遇到问题。限制是它无法呈现视图(绘图)。有没有人有任何提示如何解决这个问题?

类视图(http://developer.android.com/reference/android/view/View.html)的文档对Android用于呈现视图的步骤有一些解释。在这种情况下,我们将进入“布局”,而不是“绘图”。有任何想法的人可以展示一个例子吗?

我的代码正在生成异常: 错误 - >宽度和高度必须> 0

...
public static Bitmap loadBitmapFromView(View v) {
    Bitmap b = null;
    try {
        b = Bitmap.createBitmap(
                v.getWidth(),
                v.getHeight(), 
                Bitmap.Config.ARGB_8888);                
        Canvas c = new Canvas(b);
        v.measure(v.getWidth(), v.getHeight()); 
        v.layout(0, 0, v.getWidth(), v.getHeight());
        v.draw(c);

    } catch (Exception e) {

        Log.e(MainActivity.TAG, "error -> "+e.getMessage());
    }



    return b;
}


public void snap(View v) {


    LayoutInflater inflate = (LayoutInflater) getBaseContext()
            .getSystemService(LAYOUT_INFLATER_SERVICE);
    View view = new View(getBaseContext());
    view = inflate.inflate(R.layout.list_item, null);


    Log.d(MainActivity.TAG, "getWidth -> "+view.getWidth());
    Log.d(MainActivity.TAG, "getHeight   -> "+view.getHeight());

    Bitmap b = loadBitmapFromView(view);
    if (b != null) {

        LinearLayout mainLayout = (LinearLayout) findViewById(R.id.LinearLayout1);
        ImageView image = new ImageView(this);
        image.setImageBitmap(b);

        mainLayout.addView(image);
    }


}

2 个答案:

答案 0 :(得分:8)

我通过这种方式找到了解决方案:

public static Bitmap getScreenViewBitmap(final View v) {
    v.setDrawingCacheEnabled(true);

    v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
    v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());

    v.buildDrawingCache(true);
    Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
    v.setDrawingCacheEnabled(false); // clear drawing cache

    return b;
}

答案 1 :(得分:1)

在充气后你会立即尝试获取视图的宽度和高度,但View在布局之后才会有大小。您可以自己确定大小(使用适当的measure()调用MeasureSpec)或将其作为布局的一部分,设置为Invisible,并且仅尝试从View中加载Bitmap它已经布局了。