2

我们在从特定视图生成位图时遇到了问题。限制是它不能被渲染视图(绘图)。有没有人有任何提示如何解决这个问题?

类视图的文档 ( 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);
    }


}
4

2 回答 2

9

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

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;
}
于 2013-05-18T12:26:54.057 回答
1

您立即尝试在膨胀后获取视图的宽度和高度,但视图在布局之后才具有大小。您可以自己确定其大小(measure()使用MeasureSpec适当的调用)或将其作为布局的一部分,设置为不可见,并且仅在布局后尝试从视图中加载位图。

于 2013-05-16T23:19:49.597 回答