[英]Programatically generate view and capture bitmap
I'm programmatically generating a view in Android. 我正在以编程方式在Android中生成视图。 The parent view is a
RelativeLayout
and I'm adding subviews dynamically (eg TextView
and ImageView
). 父视图是
RelativeLayout
,我正在动态添加子视图(例如TextView
和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);
But when I add this bitmap to an ImageView it doesn't show anything. 但是,当我将此位图添加到ImageView时,它什么也没有显示。
What am I doing wrong? 我究竟做错了什么? I want to generate a view, turn it into a bitmap but not display it on the screen.
我想生成一个视图,将其转换为位图,但不显示在屏幕上。
Any help would be appreciated. 任何帮助,将不胜感激。
Well, you definitely do not have a call to layout()
after measure()
, which AFAIK is required here. 好吧,您肯定没有在
measure()
之后调用layout()
measure()
,这里需要AFAIK。
Whether you can get away with View.MeasureSpec.UNSPECIFIED
and stuff like getMeasuredWidth()
, I can't say, as I haven't tried that. 无论您是否可以使用
View.MeasureSpec.UNSPECIFIED
和诸如getMeasuredWidth()
类的东西,我都不能说,因为我还没有尝试过。 Whenever I have manually measured and laid out a View
, I have always used actual sizes, such as: 每当我手动测量并布置
View
,我总是使用实际尺寸,例如:
root=inflater.inflate(R.layout.add, null);
root.measure(800, 480);
root.layout(0, 0, 800, 480);
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
. 如果您的
Bitmap
当前具有有用的大小,但没有任何内容,请在绘制到Canvas
之前尝试使用具有该大小的layout()
。 If your Bitmap
wound up with some less-than-useful size (eg, one or both dimensions are 0), you will probably need to specify an actual size rather than go UNSPECIFIED
. 如果您的
Bitmap
大小用了一些不到用的大小(例如,一个或两个维度都为0),则可能需要指定实际大小,而不要指定UNSPECIFIED
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.