如何打印屏幕布局的单个部分



提前感谢您的关注。

我只需要在布局的一部分而不是全部中打印屏幕。例如,下面我有 2 个cardViews,其中一个只是一个随机cardview,我只想保存第二个cardView的一个图像,其中包含文本"我想打印屏幕只是这个CardView",只有它,而不是布局中的所有其余对象。

图片示例在这里

我不知道该怎么做。有没有人遇到过同样的困难或知道我该怎么做?再次感谢。

试试这个。

CardView card = (CardView) findViewById(R.id.card);

现在只需将卡传递给captureScreenShot((。它返回位图并保存该位图saveImage((。

您可以传递任何视图,如RelativeLayout,LinearLayout等,任何视图都可以传递给captureScreenShot((。

// Function which capture Screenshot
public Bitmap captureScreenShot(View view) {
    /*
     * Creating a Bitmap of view with ARGB_4444.
     * */
    Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_4444);
    Canvas canvas = new Canvas(bitmap);
    Drawable backgroundDrawable = view.getBackground();
    if (backgroundDrawable != null) {
        backgroundDrawable.draw(canvas);
    } else {
        canvas.drawColor(Color.parseColor("#80000000"));
    }
    view.draw(canvas);
    return bitmap;
}
// Function which Save image.
private void saveImage(Bitmap bitmap) {
    File file = // Your Storage directory name + your filename
    if (file == null) {
        return;
    }
    try {
        FileOutputStream fos = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

最后像这样调用这个函数。

saveImage(captureScreenShot(card));

然后获取卡片视图的ID:

CardView view = (CardView )findViewById(R.id.card_view);
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bm = view.getDrawingCache();

最新更新