android 将以编程方式创建的视图绘制为位图

whhtz7ly  于 2023-01-03  发布在  Android
关注(0)|答案(1)|浏览(128)

我正在尝试使用绘图缓存来制作一个以编程方式创建的视图的位图,如下所示:

LinearLayout view = new LinearLayout(context);
view.setBackground(context.getResources().getColor(R.color.green));
view.setDrawingCacheEnabled(true);

int width = View.MeasureSpec.makeMeasureSpec(800, View.MeasureSpec.EXACTLY);
int height = View.MeasureSpec.makeMeasureSpec(600, View.MeasureSpec.EXACTLY); 
view.measure(w, h);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.buildDrawingCache(true);

Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());

我期望它输出一个800 x600的绿色位图;相反,我得到了一个800 x600的白色位图。我做错了什么?

w80xi6nr

w80xi6nr1#

多亏了@CommonsWare,这才行得通:

LinearLayout view = new LinearLayout(context);
    view.setBackgroundColor(context.getResources().getColor(R.color.green));
    int width = View.MeasureSpec.makeMeasureSpec(800, View.MeasureSpec.EXACTLY);
    int height = View.MeasureSpec.makeMeasureSpec(600, View.MeasureSpec.EXACTLY); 
    view.measure(width, height);

    Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
    view.draw(canvas);

相关问题