12

简短的问题:

假设我有某种布局文件并且我对它进行膨胀(或在代码中使用普通的 CTOR)。

我不想显示膨胀的视图,而是希望在某些限制下(给定宽度和高度,甚至比屏幕更大)拍摄一个“屏幕截图”(位图)。

我不希望将视图添加到屏幕上的任何位置,而只是为了这个目的而保留它,以后可能会添加它。

这样的东西对于轻松操作如何放置东西可能很有用。例如,我可以使用将图像放入其中的布局,以便它周围有一个框架。

这样的事情可能吗?如果是这样,如何?

4

1 回答 1

14

好的,基于此链接,我找到了一种可能的方法:

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

}
于 2014-10-04T22:00:03.380 回答