最简单的方法当然是使用adb
adb shell screencap -p >screenshot.png
不过有些app会限制adb进行截图,这个时候adb截屏为黑屏
此时有两种方法获取截图
第一使用模拟器自带截图快捷键,获取安卓自带截图键,逍遥模拟器为alt+F3
可模拟键盘输入按键(自行百度)
第二种:使用winapi + 电脑屏幕截图
以下为C#代码,python请自行转换(memu为逍遥模拟器的窗口名称)
先获取模拟器句柄,然后使窗口显示,根据窗口大小和位置截图,然后隐藏窗口
/// <summary>
/// 获取模拟器截屏
/// </summary>
/// <param name="num"></param>
public static Bitmap GetEmulatorScreen(int num)
{
Process[] procList = Process.GetProcessesByName("memu");
for (int i = 0; i < 20; i++)
{
if (i == num)
{
IntPtr handle = procList[i].MainWindowHandle;
ShowWindow(handle, 1);
RECT rECT = new RECT();
GetWindowRect(handle, ref rECT);
Task.Delay(200).Wait();
Bitmap bitmap = ScreenShot.GetScreen(rECT.Left, rECT.Top, rECT.Right, rECT.Bottom);
ShowWindow(handle, 2);
return bitmap;
}
}
return null;
}
/// <summary>
/// 获取窗口位置
/// </summary>
/// <param name="hWnd"></param>
/// <param name="lpRect"></param>
/// <returns></returns>
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int Left; //最左坐标
public int Top; //最上坐标
public int Right; //最右坐标
public int Bottom; //最下坐标
}
/// <summary>
/// 显示窗口
/// 0 关闭窗口
/// 1 正常大小显示窗口
/// 2 最小化窗口
/// 3 最大化窗口
/// </summary>
/// <param name="hwnd"></param>
/// <param name="nCmdShow"></param>
/// <returns></returns>
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern int ShowWindow(IntPtr hwnd, int nCmdShow);
/// <summary>
/// 获取屏幕
/// </summary>
/// <param name="sourceX">左上角x</param>
/// <param name="sourceY">左上角y</param>
/// <param name="destinationX">右下角x</param>
/// <param name="destinationY">右下角y</param>
/// <returns></returns>
public static Bitmap GetScreen(int sourceX, int sourceY, int destinationX, int destinationY)
{
if(sourceX < 0)
{
sourceX = 0;
}
if (sourceY < 0)
{
sourceY = 0;
}
if(destinationY <= sourceY)
{
destinationY = sourceY + 10;
}
int Width = destinationX - sourceX;
int Height = destinationY - sourceY;
Bitmap bmSave = GetScreen();
Graphics g = Graphics.FromImage(bmSave);//绘制这个图像
g.CopyFromScreen(sourceX, sourceY, destinationX, destinationY, new Size(Width, Height), CopyPixelOperation.SourceCopy);
// 2.New一个指定规格的新图片(参数为规格大小)
Bitmap tempBitmap = new Bitmap(Width, Height);
//3.将新图片绑定到Graphics
Graphics graphics = Graphics.FromImage(tempBitmap);
//4.截图图片(原图,新图片的矩形参数,需要截取的矩形区域参数,像素度量单位)
graphics.DrawImage(bmSave, new Rectangle(0, 0, Width, Height), new Rectangle(sourceX, sourceY, Width, Height), GraphicsUnit.Pixel);
return tempBitmap;
}
/// <summary>
/// 获取全屏截图
/// </summary>
/// <returns></returns>
public static Bitmap GetScreen()
{
Bitmap bmSave = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics g = Graphics.FromImage(bmSave);//绘制这个图像
g.CopyFromScreen(0, 0, 0, 0, new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height), CopyPixelOperation.SourceCopy);
return bmSave;
}