鸿蒙开发实战-手写一个Openharmony投屏工具

实战手写一个Openharmony投屏工具,实现代码分享如下:

java
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImageFrame extends JFrame {

    private BufferedImage originalImage;
    private final String imagePath = System.getProperty("user.dir") + File.separator + "scr.jpeg"; // 图片文件的路径
    private final double aspectRatio = 720.0 / 1280.0; // 定义比例
    private ImagePanel imagePanel;
    private long pressTime; // 用于记录鼠标按下的时间
    private int initWidth = 517;  //初始窗口宽
    private int initHeight = 908;   //初始窗口高

    public ImageFrame() {
        setTitle("OHScrcpy(by zhonghongfa)");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // setLocationRelativeTo(null);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int screenWidth = screenSize.width;
        int screenHeight = screenSize.height;
        // 计算窗体在屏幕右侧的新位置
        int x = screenWidth - initWidth - 50;
        int y = 50; // 如果希望窗体垂直居中
        // 设置窗体的新位置
        setLocation(x, y);

        loadImage();
        imagePanel = new ImagePanel();
        add(imagePanel);
        setIconImage();

        addComponentListener(new ComponentAdapter() {
            public void componentResized(ComponentEvent e) {
                maintainAspectRatio();
            }
        });

        imagePanel.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                pressTime = System.currentTimeMillis(); // 记录鼠标按下的时间
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                long releaseTime = System.currentTimeMillis(); // 记录鼠标释放的时间
                double scaleX = (double) originalImage.getWidth() / imagePanel.getWidth();
                double scaleY = (double) originalImage.getHeight() / imagePanel.getHeight();
                int realX = (int) (e.getX() * scaleX);
                int realY = (int) (e.getY() * scaleY);
                if (releaseTime - pressTime > 500) { // 如果按下时间超过500毫秒,则认为是长按
                    System.out.println("Real Long pressed coordinates: (" + realX + ", " + realY + ")");
                    executeCommand(String.format("hdc shell uitest uiInput longClick %d %d", realX, realY));
                }else{
                    System.out.println("Real clicked coordinates: (" + realX + ", " + realY + ")");
                    // 构建并执行命令
                    executeCommand(String.format("hdc shell uitest uiInput click %d %d", realX, realY));
                }
            }
        });

        setSize(initWidth, initHeight); // 设置初始窗口大小
        new Timer(100, e -> updateImageAndReload()).start();
    }

    private void setIconImage() {
        try {
            BufferedImage iconImage = ImageIO.read(getClass().getResource("/OHScrcpy.png")); // 注意路径前的斜杠
            setIconImage(iconImage);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void loadImage() {
        try {
            File imageFile = new File(imagePath);
            if (imageFile.exists()) {
                originalImage = ImageIO.read(imageFile);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void executeCommand(String command) {
        try {
            System.out.println("Executing command: " + command);
            Process process = Runtime.getRuntime().exec("cmd.exe /c " + command);
            process.waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void updateImage() {
        try {
            // 执行外部命令更新图片
            String[] cmd = {
                    "cmd.exe",
                    "/c",
                    "hdc shell rm -rf /data/local/tmp/scr.jpeg & hdc shell snapshot_display -f /data/local/tmp/scr.jpeg & hdc file recv  /data/local/tmp/scr.jpeg"
            };
            Process p = Runtime.getRuntime().exec(cmd);
            p.waitFor(); // 等待命令执行完成

        } catch (IOException | InterruptedException ex) {
            ex.printStackTrace();
        }
    }

    private void updateImageAndReload() {
        updateImage();
        loadImage();
        imagePanel.repaint();
    }

    private void maintainAspectRatio() {
        Rectangle bounds = this.getBounds();
        int width = bounds.width;
        int height = (int) (width / aspectRatio);
        if (height != bounds.height) {
            this.setSize(width, height);
        }
    }

    // JPanel 的子类用于绘制图像
    private class ImagePanel extends JPanel {
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (originalImage != null) {
                g.drawImage(originalImage, 0, 0, getWidth(), getHeight(), this); // 动态调整图片大小
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new ImageFrame().setVisible(true));
    }
}


运行效果如下

Openharmony投屏工具_Java

485f48c927688f7ba739dc1871e0214e.jpeg


http://www.niftyadmin.cn/n/5394697.html

相关文章

学习JAVA的第七天(基础)

目录 static 静态变量 静态方法 工具类: static的注意事项 继承 继承的好处 继承的特点 方法的重写 书写格式 override重写注解 方法重写的要求 this关键字 super关键字 static static表示静态,是Java中的一个修饰符,可以修饰成…

STL - 图

1、图的基本概念 图是由顶点集合及顶点间的关系组成的一种数据结构&#xff1a;G (V&#xff0c; E)&#xff0c;其中&#xff1a; 顶点集合 V {x|x属于某个数据对象集}是有穷非空集合&#xff1b; 边的集合 E {(x,y)|x,y属于V}或者E {<x&#xff0c;y>|x,y属于V …

pytest-fixture固件的使用

fixture 固件&#xff1a;pytest自动化中用于前后置&#xff0c;功能强大&#xff0c;可替代setup,teardown,setup_class,teardown_class 装饰器&#xff1a; pytest.fixture(scope"作用域“, params"参数化", autouse”自动执行“, ids”参数别名“, name"…

接口测试 —— Jmeter读取数据库数据作测试参数

1、添加Jdbc Request 2、添加ForEach控制器(右键线程组->逻辑控制器->ForEach控制器) ①输入变量的前缀&#xff1a;mobilephone&#xff1b; 从jdbc request设置的变量得知&#xff0c;我们要取的值为mobilephone_1、mobilephone_2、mobilephone_3......所以这里输入m…

记录一下 Unity团结引擎开发OpenHarmony Next 应用 环境搭建流程

原视频链接 记录环境搭建过程~&#xff0c;本文是图文版本 一、打开团结引擎官网下载对应的 团结引擎版本 官网地址&#xff1a;https://unity.cn/tuanjie/releases 根据各自的开发环境下载对应的软件版本&#xff0c;我是 windwos 环境&#xff0c;我就下载 windows 环境 …

mac 配置faas 全局二进制命令

FaaS&#xff08;即功能即服务-Function as a Services&#xff09;是一种云计算服务&#xff0c;允许客户执行代码来响应事件&#xff0c;而无需管理通常与构建和启动微服务应用程序相关的复杂基础架构 在互联网上托管软件应用程序通常需要配置和管理虚拟服务器或物理服务器&…

关于python的数据可视化与可视化:数据读取

带着问题寻找答案可以使自己不再迷茫或者不知所措&#xff01; 了解什么python的数据可视化&#xff1f; 数据的读取&#xff08;一般伴随着课程文件中会进行提供和利用&#xff09; 数据可视化是将Python应用于大气海洋科学中数据处理及分析过程的重要环节&#xff0c;它可以…

如何在 CentOS 中配置 SSH 服务的 TCP 端口转发

在 CentOS 系统中&#xff0c;SSH&#xff08;Secure Shell&#xff09;服务提供了强大的功能&#xff0c;其中之一就是 TCP 端口转发。通过此功能&#xff0c;我们可以安全地将本地或远程服务器上的端口流量转发到其他主机上。本文将引导您如何在 CentOS 中启用或禁用 SSH 的 …