【问题标题】:Is it possible to take a screenshot of a view, without showing the view?是否可以在不显示视图的情况下截取视图?
【发布时间】:2013-06-19 11:18:53
【问题描述】:

小问题:

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

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

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

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

这样的事情可能吗?如果有,怎么做?

【问题讨论】:

  • 这是测试应用程序吗?如果是,那么您可以检查 com.android.systemui.screenshot.ScreenshotTest
  • “测试应用”是什么意思?我想知道任何类型的应用程序。
  • 我目前无法测试它,但视图draw-method 应该能够绘制到画布上,即使它没有添加到任何布局中。但是,您确实需要完成其生命周期的所有布局阶段。 developer.android.com/reference/android/view/…
  • 我如何让它们全部绘制到位图而不是屏幕上,而不是真正将它们添加到真实的视图层次结构中?

标签: android screenshot android-view android-inflate


【解决方案1】:

好的,我找到了一种可能的方法,基于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);
    }

}

【讨论】:

  • @Nerves82 自上次以来已更改。我永远不会把这么有问题的东西放在这里。此外,VirusTotal 表示没问题,基于 67 种防病毒软件:virustotal.com/en/url/…virustotal.com/en/url/…
  • @Nerves82 无论如何,更新链接以显示以前的内容,使用 Wayback
  • 太棒了。我认为它在发布答案后的 2 年内发生了变化,但更安全的是抱歉。感谢您如此迅速地编辑它。
  • 如果从现有视图绘制,请使用 buildDrawingCache()/destroyDrawingCache() 强制创建绘图缓存。
猜你喜欢
  • 1970-01-01
  • 2015-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多