以编程方式生成视图和捕获位图 [英] Programatically generate view and capture bitmap

查看:50
本文介绍了以编程方式生成视图和捕获位图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在以编程方式在 Android 中生成视图.父视图是一个 RelativeLayout,我正在动态添加子视图(例如 TextViewImageView).

I'm programmatically generating a view in Android. The parent view is a RelativeLayout and I'm adding subviews dynamically (e.g. TextView and ImageView).

如果我将视图添加到我的活动的主视图中,它就会显示正常(正如预期的那样).使用此代码.

If I add the view to my activity's main view then it displays fine (just as expected). Using this code.

LinearLayout mainView = (LinearLayout)findViewById(R.id.mainView);
mainView.addView(dynamicallyGeneratedView);

虽然我不想将视图添加为子视图,但我只想将其转换为位图.所以我做了以下事情:

I don't want to add the view as a subview though, I just want to turn it into a bitmap. So I do the following:

view.measure(View.MeasureSpec.UNSPECIFIED,View.MeasureSpec.UNSPECIFIED);
Bitmap b = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
view.draw(c);

但是当我将此位图添加到 ImageView 时,它不显示任何内容.

But when I add this bitmap to an ImageView it doesn't show anything.

我做错了什么?我想生成一个视图,将其转换为位图,但将其显示在屏幕上.

What am I doing wrong? I want to generate a view, turn it into a bitmap but not display it on the screen.

任何帮助将不胜感激.

推荐答案

好吧,你肯定没有在 measure() 之后调用 layout(),它此处需要 AFAIK.

Well, you definitely do not have a call to layout() after measure(), which AFAIK is required here.

是否可以使用 View.MeasureSpec.UNSPECIFIED 和诸如 getMeasuredWidth() 之类的东西,我不能说,因为我还没有尝试过.每当我手动测量并布置View时,我总是使用实际尺寸,例如:

Whether you can get away with View.MeasureSpec.UNSPECIFIED and stuff like getMeasuredWidth(), I can't say, as I haven't tried that. Whenever I have manually measured and laid out a View, I have always used actual sizes, such as:

root=inflater.inflate(R.layout.add, null);
root.measure(800, 480);
root.layout(0, 0, 800, 480);

如果您的 Bitmap 目前有一个有用的大小,但没有任何内容,请在绘制到 Canvas 之前尝试使用该大小的 layout().如果您的 Bitmap 最终使用了一些不太有用的尺寸(例如,一个或两个尺寸为 0),您可能需要指定实际尺寸而不是 UNSPECIFIED.

If your Bitmap presently has a useful size, but just does not have any content, try layout() with the size before you draw to the Canvas. If your Bitmap wound up with some less-than-useful size (e.g., one or both dimensions are 0), you will probably need to specify an actual size rather than go UNSPECIFIED.

这篇关于以编程方式生成视图和捕获位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆