Airtest provides API for screenshot whole screen and crop image.
from airtest.aircv import *
whole_scr = G.DEVICE.snapshot()
# rect = [x_min, y_min, x_max, y_max]
ele_snapshot = toggle_snap = crop_image(whole_scr,rect)
Elements' position coordinates and size can be acquired. We can calculate the rectangle range by these 2 parameters.
pos = target_ele.get_position()
size = target_ele.get_size()
The full code:
from airtest.core.api import *
from airtest.aircv import *
from airtest.aircv.utils import cv2_2_pil
target_ele = poco('xxx')
# position and size
pos = target_ele.get_position()
size = target_ele.get_size()
# rectangle coordinates(absulute)
absolute_a = [pos[0]-size[0]/2, pos[1]-size[1]/2]
absolute_b = [pos[0]+size[0]/2, pos[1]+size[1]/2]
# screen resolution
w,h = device().get_current_resolution()
# relative coordinates
relative_a = [absolut_a[0] * w, absolut_a[1] * h]
relative_b = [absulut_b[0] * w, absulut_b[1] * h]
# snapshot
snap = G.DEVICE.snapshot()
toggle_snap = crop_image(snap,(relative_a[0], relative_a[1], relative_b[0], relative_b[1]))
# save snapshot
target_ele_img = cv2_2_pil(target_ele_snap)
target_ele_img.save('./target_ele.png')