Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 Python 自動生成 Android 多分辨率圖片

編輯:關於 Android 程式設計

Android 屏幕分辨率適配的圖標處理向來麻煩,讓 UI 為每個尺寸都出一張圖既浪費時間又容易出錯。於是筆者用 Python 寫了個小工具來自動化處理:UI 只需提供 1080×1920 分辨率下的圖片,放進 drawable-xxhdpi 目錄,其餘分辨率的圖片由腳本自動生成。

import os.path
import sys
from PIL import Image

"""
自動生成不同分辨率下的 App 圖片
UI 設計 1080*1920 分辨率圖片,放在 drawable-xxhdpi 目錄下,自動生成其它的分辨率圖片
"""

__author__ = ['"Xitao":']

def image_resize(img_file, target, percent):
    """resize image and save to target path
    :param img_file: image file path
    :param target: save path
    :param percent: resize percent
    :return:
    """
    img = Image.open(img_file)
    print(img.size)
    width, height = img.size
    target_img = img.resize((int(width * percent), int(height * percent)), Image.ANTIALIAS)
    target_img.save(target)
    img.close()
    target_img.close()
    print(" save target image to " + target)

def path_resize(src, target, percent):
    if not os.path.isdir(src):
        print(src + " must be a dir")
        return -1
    os.chdir(src)
    cwd = os.getcwd()
    dirs = os.listdir(cwd)
    for file_name in dirs:
        print(file_name)
        if file_name.endswith('.9.png'):
            continue
        src_file = os.path.join(cwd, file_name)
        if not os.path.exists(target):
            os.mkdir(target)
        image_resize(src_file, target + '/' + file_name, percent)

def android(res_dir):
    xxhdpi_path = res_dir + "/drawable-xxhdpi/"
    if not os.path.isdir(xxhdpi_path):
        print("xxhdpi_path must be a dir")
        return -1
    path_resize(xxhdpi_path, res_dir + '/drawable-xhdpi', 0.667)
    path_resize(xxhdpi_path, res_dir + '/drawable-hdpi', 0.444)
    path_resize(xxhdpi_path, res_dir + '/drawable-mdpi', 0.296)

if __name__ == "__main__":
    print('please input your android res dir path')
    print(sys.argv)
    if sys.argv[1]:
        android(sys.argv[1])

腳本的核心思路是:以 xxhdpi 目錄為基準,按不同比例縮放,分別輸出到 xhdpi(0.667)、hdpi(0.444)、mdpi(0.296)等目錄;同時自動跳過 .9.png 這類點九圖。運行時把 res 目錄路徑作為參數傳入即可,一鍵生成整套多分辨率圖片。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved