是否有可能采取视图的截图,没有显示的看法? [英] Is it possible to take a screenshot of a view, without showing the view?
问题描述
短的问题:
假设我有某种布局文件和我它充气(或使用code正常的构建函数)。
Suppose I have some kind of a layout file and I inflate it (or use the normal CTORs in code).
而不是显示膨胀的观点,我想采取截屏它会是什么样子下(给定的宽度和放大器;高度,甚至比屏幕大)一些限制(位图)。
Instead of showing the inflated view, I wish to take a "screenshot" (a bitmap) of how it would look like under some limitations (of given width&height, even larger than the screen).
我不希望将视图添加到在屏幕任意位置,但只持有它用于此目的,也许以后添加它。
I do not wish to add the view to anywhere on the screen, but only hold it for this purpose and maybe add it later.
这样的事情可能是,如何把东西容易操作非常有用。例如,我可以使用该图像将里面放一个布局,以便它周围有一个框架。
Such a thing could be useful for easy manipulations of how to place things. For example, I could use a layout that an image would be put inside it so that it would have a frame around it.
这种事可能吗?如果是这样,怎么样?
Is such a thing possible? If so, How?
推荐答案
好吧,我已经找到了一种可能的方式做到这一点的基础上的 此链接 :
OK, I've found a possible way to do it, based on this link :
public static Bitmap drawToBitmap(Context context,final int layoutResId,final int width,final int height)
{
final Bitmap bmp=Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
final Canvas canvas=new Canvas(bmp);
final LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View layout=inflater.inflate(layoutResId,null);
layout.setDrawingCacheEnabled(true); layout.measure(MeasureSpec.makeMeasureSpec(canvas.getWidth(),MeasureSpec.EXACTLY),MeasureSpec.makeMeasureSpec(canvas.getHeight(),MeasureSpec.EXACTLY));
layout.layout(0,0,layout.getMeasuredWidth(),layout.getMeasuredHeight());
canvas.drawBitmap(layout.getDrawingCache(),0,0,new Paint());
return bmp;
}
使用示例:
public class MainActivity extends ActionBarActivity
{
@Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView iv=(ImageView)findViewById(R.id.image);
final DisplayMetrics metrics=getResources().getDisplayMetrics();
final Bitmap b=drawToBitmap(this,R.layout.test,metrics.widthPixels,metrics.heightPixels);
iv.setImageBitmap(b);
}
}
这篇关于是否有可能采取视图的截图,没有显示的看法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!