【Android】多种方式实现截图(屏幕截图、控件截图、长图)

目录

  • 1. View截图
  • 2. WebView截图
  • 3. 屏幕截图
  • 格式转换方法

Android 截图主要为四种:View 截图、WebView 截图、屏幕截图、系统截图和 adb 截图。后两种截图不常用,不详细展开。

1. View截图

可以截取到View不可见的部分,生成长图,状态栏和导航栏无法截到

fun screenshotView(view: ViewGroup):Bitmap?{
    var h = 0
    var bitmap:Bitmap?=null
    for(i in 0 until view.childCount){
        h += view.getChildAt(i).height
        view.getChildAt(i).setBackgroundColor(Color.parseColor("#6CC287"))
    }
    bitmap = Bitmap.createBitmap(view.width, h, Bitmap.Config.RGB_565)
    val canvas = Canvas(bitmap)
    view.draw(canvas)
    //重新赋色
    for(i in 0 until view.childCount){
        view.getChildAt(i).setBackgroundDrawable(null)
    }
    return bitmap
}

2. WebView截图

// 1.capturePicture方法废弃
// 2.getScale方法废弃

// 3.getDrawingCache方法
private static byte[] screenshotWebView() {
  Bitmap bitmap = webView.getDrawingCache();
  byte[] drawByte = getBitmapByte(bmp);
  return drawByte;
}

// 4.draw方法
private static byte[] screenshotWebView() {
  // webView.setDrawingCacheEnabled(true); 设置缓存
  Bitmap bitmap = Bitmap.createBitmap(webView.getWidth(), webView.getHeight(), Bitmap.Config.ARGB_8888);
  Canvas canvas = new Canvas(bitmap);
  webView.draw(canvas);
  webView.destroyDrawingCache();
  byte[] drawByte = getBitmapByte(bitmap);
  return drawByte;
}

可能会截取不到 cavans 元素,原因是开启了硬件加速(关闭硬件加速可能导致页面异常),可在 AndroidManifest.xml 中设置:

android:hardwareAccelerated="false"

截长图的话需要配置:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  WebView.enableSlowWholeDocumentDraw();
}
setContentView(R.layout.webview);

3. 屏幕截图

截取应用当前屏幕的图片:

	/**
     * 获取当前屏幕截图,包含状态栏
     *
     * @param activity activity
     * @return Bitmap
     */
    public static Bitmap captureWithStatusBar(Activity activity) {
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bmp = view.getDrawingCache();
        int width = getScreenWidth(activity);
        int height = getScreenHeight(activity);
        Bitmap ret = Bitmap.createBitmap(bmp, 0, 0, width, height);
        view.destroyDrawingCache();
        return ret;
    }

    /**
     * 获取当前屏幕截图,不包含状态栏
     *
     * @param activity activity
     * @return Bitmap
     */
    public static Bitmap captureWithoutStatusBar(Activity activity) {
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bmp = view.getDrawingCache();
        int statusBarHeight = getStatusBarHeight(activity);
        int width = getScreenWidth(activity);
        int height = getScreenHeight(activity);
        Bitmap ret = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height - statusBarHeight);
        view.destroyDrawingCache();
        return ret;
    }

	/**
     * 得到屏幕的高
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        int height = wm.getDefaultDisplay().getHeight();
        return height;
    }

    /**
     * 得到屏幕的宽
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        return width;
    }

	/**
     * 获取状态栏高度
     *
     * @param context 上下文
     * @return 状态栏高度
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources()
                .getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

格式转换方法

// Bitmap 转 Base64
private static String getBitmapString(Bitmap bitmap) {
  String result = null;
  ByteArrayOutputStream out = null;
  try {
    if (bitmap != null) {
      out = new ByteArrayOutputStream();
      bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
​
      out.flush();
      out.close();byte[] bitmapBytes = out.toByteArray();
      result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
    }
  } catch (IOException e) {
      e.printStackTrace();
  } finally {
    try {
      if (out != null) {
          out.flush();
          out.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  return result;
}// Bitmap 转 Byte
private static byte[] getBitmapByte(Bitmap bitmap){
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  // 转换类型,压缩质量,字节流资源
  bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
  try {
      out.flush();
      out.close();
  } catch (IOException e) {
      e.printStackTrace();
  }
  return out.toByteArray();
}

// Drawable 转 Bitmap
public static Bitmap toBitmap(Drawable drawable) {
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable) drawable).getBitmap();
    } else if (drawable instanceof ColorDrawable) {
        //color
        Bitmap bitmap = Bitmap.createBitmap(32, 32, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(((ColorDrawable) drawable).getColor());
        return bitmap;
    } else if (drawable instanceof NinePatchDrawable) {
        //.9.png
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }
    return null;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/733108.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

会自动清除的文件——tempfile

原文链接:http://www.juzicode.com/python-tutorial-tempfile/ 在某些不需要持久保存文件的场景下,可以用tempfile模块生成临时文件或者文件夹,这些临时文件或者文件夹在使用完之后就会自动删除。 NamedTemporaryFile用来创建临时文件&…

教程:LVM操作讲解

LVM简介 在系统运维过程中,对磁盘扩缩容是常见的操作。如何高效的管理磁盘容量,lvm提供了很好的解决方案。 LVM将磁盘抽象成PV、VG、LV,方便用户进行磁盘管理,简单来讲,是由物理磁盘划分成PV,PV加入到具体…

探索Linux的奇妙世界:第二关---Linux的基本指令1

1. xshell与服务器的连接 想必大家在看过上一期视频时已经搭建好了Linux的环境了并且已经下好了终端---xshell了吧?让我来带大家看一看下好了是什么样子的: 第一次登陆会让你连接你的服务器,就是我们买的云服务器,买完之后需要把公网地址ip复制过来进行链接,需要用户名和密码连…

CNN神经网络猫狗分类经典案例

因为有猫和狗两类,所有在data/train目录下,再建两个目录data/train/dog和data/train/cat: 同理,其他的data/validation和data/test目录下,再建两个目录:cat和data/,在cat和dog目录下&#xff0c…

Large Language Model based Multi-Agents: A Survey of Progress and Challenges

目录 摘要简介背景单一智能体系统单智能体 vs .多智能体系统 剖析多智能体系统:接口、剖析、通信和能力智能体 - 环境接口智能体画像智能体通信能力获取 摘要 大型语言模型( Large Language Models,LLMs )在各种任务中都取得了令人瞩目的成功。由于LLMs…

你好,复变函数2.0

第一行&#xff1a;0 或 1 第二行&#xff1a;&#xff08;空格&#xff09;函数&#xff08;后缀&#xff09; #pragma warning(disable:4996) #include <easyx.h> #include <stdio.h> #include <math.h> #define PI 3.141592653589793 #define E 2.71828…

【ai】tritonserver 的测试sdk部署

HybrIKHybrIK 环境 conda create -n hybrik python=3.8 -y 虚拟环境 zhangbin@ubuntu-server:~/miniconda3/bin$ pip config set global.index-url https: …

make与makefile

目录 一、make的默认目标文件与自动推导 二、不能连续make的原因 执行原理 touch .PHONY伪目标 make指令不回显 makefile多文件管理 简写依赖方法 三、回车与换行 四、缓冲区 一、make的默认目标文件与自动推导 假设这是一个makefile文件&#xff0c;make的时候默认生…

Kubernetes Dashboard

Minikube 环境搭建 Kubernetes 的基本架构 Kubernetes 声明式语言 YAML YAML操作Kubernetes核心对象 CentOs搭建Kubernetes集群 Kubernetes进阶对象Deployment、DaemonSet、Service Kubernetes进阶对象Ingress、Ingress Class、Ingress Controller Kubernetes集群部署项目实践 …

XTDrone-无人机与无人船协同初步-配置教程

说明&#xff1a;配置该教程时所使用的是Ubuntu20.04 1 海洋与无人船仿真环境搭建 cp -r ~/XTDrone/sitl_config/usv/* ~/catkin_ws/src/ cd catkin_ws catkin build # or catkin_make 说明&#xff1a;由于官方所编写的脚本时几年之前的&#xff0c;所以很多东西不符合现在…

深入分析并可视化城市轨道数据

介绍 中国城市化进程加速中&#xff0c;城市轨道交通的迅速扩张成为提升城市运行效率和居民生活品质的关键。这一网络从少数大城市延伸至众多大中型城市&#xff0c;映射了经济飞跃和城市管理现代化。深入分析并可视化城市轨道数据&#xff0c;对于揭示网络特性、评估效率、理…

JavaScript学习笔记(二)

12、数字 常规用法和java的用法相似&#xff0c;就不再做详细的记录, JavaScript 数字 以下只记录特殊用法&#xff1a; 12.1 数字字符串运算 在所有数字运算中&#xff0c;JavaScript 会尝试将字符串转换为数字&#xff1a; var x "100"; var y "10"…

MySQL性能问题诊断方法和常用工具

作者介绍&#xff1a;老苏&#xff0c;10余年DBA工作运维经验&#xff0c;擅长Oracle、MySQL、PG数据库运维&#xff08;如安装迁移&#xff0c;性能优化、故障应急处理等&#xff09; 公众号&#xff1a;老苏畅谈运维 欢迎关注本人公众号&#xff0c;更多精彩与您分享。MySQL运…

python入门基础知识(错误和异常)

本文部分内容来自菜鸟教程Python 基础教程 | 菜鸟教程 (runoob.com) 本人负责概括总结代码实现。 以此达到快速复习目的 目录 语法错误 异常 异常处理 try/except try/except...else try-finally 语句 抛出异常 用户自定义异常 内置异常类型 常见的标准异常类型 语法…

每天写java到期末考试--接口1--基础--6.22

规则&#xff1a; 练习&#xff1a; 抽象类的抽象方法 动物类Animal package 期末复习;public abstract class Animal {private String name;private int age;//1.空构造public Animal(){}public Animal(String name,int age){this.ageage;this.namename;}public String getNa…

【Java毕业设计】基于JavaWeb的服务出租系统

本科毕业设计论文 题目&#xff1a;房屋交易平台设计与实现 系 别&#xff1a; XX系&#xff08;全称&#xff09; 专 业&#xff1a; 软件工程 班 级&#xff1a; 软件工程15201 学生姓名&#xff1a; 学生学号&#xff1a; 指导教师&#xff1a; 导师1 导师2 文章目录 摘…

C++入门 vector部分模拟实现

目录 vector大致框架 vector常见接口模拟实现 begin迭代器 & end迭代器 capacity( ) & size( ) reserve operator[ ] push_back( ) & pop_back( ) sort vector大致框架 vector的内部的成员变量大概有三部分构成&#xff1a; namespace bit {template<c…

java中的日志

springboot自带slf4j框架和logback&#xff0c;我们可以移除spring的logging&#xff0c;然后再带入自己的日志框架。 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><exclusio…

Linux中tar压缩与解压缩

TAR是Unix/Linux中常用的归档工具&#xff0c;它可以对文件或目录进行打包但不压缩&#xff0c;或者配合其他工具进行压缩。 压缩文件或目录 以下是一些基本的tar压缩命令&#xff1a; 1.压缩单个文件&#xff1a; tar -cvf archive.tar file1 2.压缩多个文件&#xff1a; t…

毕业季带给我的五个启示

每到毕业季&#xff0c;校园里总是充满了复杂的情绪。有人欢笑&#xff0c;有人落泪。同样的四年大学生活&#xff0c;为何结局如此不同&#xff1f;本文将从多个角度探讨如何实现综合改变&#xff0c;解释在交友、机会和心态上的关键因素&#xff0c;揭示“慢就是快”的真理。…