pythonandroid-emulatoradb

How to implement zoom in and out in python with ADB?


I am trying to create a python app that can zoom in and out on a game but I cannot implement it. I am using MEmu player as my emulator and the zoom in and out function I created is not working. The swipe and tap functions I created were working but I cannot figure out how to do the zoom functionality. When running the code, it swipes to the right then after 3 seconds it swipes to the left.

Here is my code:

def zoom(zoom_in=True, duration=300, distance=100):
    # get screen size
    size_output = subprocess.check_output(["adb", "shell", "wm", "size"]).decode().strip()
    width, height = map(int, size_output.split()[-1].split('x'))
    
    # calculate start and end points
    center_x, center_y = width // 2, height // 2
    half_distance = distance // 2
    
    if zoom_in:
        start_x1, start_y1 = center_x - half_distance, center_y - half_distance
        start_x2, start_y2 = center_x + half_distance, center_y + half_distance
        end_x1, end_y1 = center_x - distance, center_y - distance
        end_x2, end_y2 = center_x + distance, center_y + distance
    else:
        start_x1, start_y1 = center_x - distance, center_y - distance
        start_x2, start_y2 = center_x + distance, center_y + distance
        end_x1, end_y1 = center_x - half_distance, center_y - half_distance
        end_x2, end_y2 = center_x + half_distance, center_y + half_distance
    
    subprocess.run([
        "adb", "shell", 
        f"input swipe {start_x1} {start_y1} {end_x1} {end_y1} {duration} && " 
        f"input swipe {start_x2} {start_y2} {end_x2} {end_y2} {duration}"
    ], shell=True)

    time.sleep(duration / 1000 + 0.1)

This is my swipe function:

def swipe_on_screen(start_x, start_y, end_x, end_y, duration=1000):
    try:
        subprocess.run(["adb","shell",f"input swipe {str(start_x)} {str(start_y)} {str(end_x)} {str(end_y)} {str(duration)}"],shell=True)
    except Exception as e:
        print(f"Error swiping on screen: {e}")

Does anyone have encountered this and found a solution?


Solution

  • Let's say you want to pinch to zoom in and out maps

    #! /usr/bin/env python3
    
    import time
    from com.dtmilano.android.viewclient import ViewClient
    
    helper = ViewClient.view_client_helper()
    oid = helper.ui_device.find_object(ui_selector='res@com.google.android.apps.maps:id/map_frame').oid
    helper.ui_object.pinch_out(oid=oid, percentage=1000, steps=50)
    time.sleep(5)
    helper.ui_object.pinch_in(oid=oid, percentage=1000, steps=50)