将编程创建的视图绘制到位图

时间:2017-01-09 22:59:02

标签: android android-layout

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

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());

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

2 个答案:

答案 0 :(得分:0)

感谢@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);

答案 1 :(得分:0)

您可以使用以下代码以编程方式创建位图

def main(TYPE, test_name, test_id=None, normalise=False):
    # ... body of script...

if __name__ == "__main__":
    parser = ...
    ...
    args = parser.parse_args()
    main(**vars(args))

希望,它会解决你的问题