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

Dou*_*ari 2 android android-canvas

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

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

我的代码生成异常:错误 - >宽度和高度必须> 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);
    }


}
Run Code Online (Sandbox Code Playgroud)

Dou*_*ari 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;
}
Run Code Online (Sandbox Code Playgroud)