그래디언트 이미지에서 Android XML 자동 생성
14331 단어 Android
디자이너가 아래 이미지 파일에 단추를 만들었다고 가정하십시오.
하지만 엔지니어는 이곳에서 곤란하다.XML에 그래디언트를 그리려면 그래디언트의 시작과 끝 색상에 대한 16진수를 입력해야 합니다.엔지니어가 컬러 투수를 가동해 RGB를 얻고 16진수로 전환하는 것은 시간이 많이 걸린다.
따라서 이미지가 매개 변수로 사용될 때 XML을 생성할 수 있는 파이썬 스크립트를 작성했습니다.이미지 라이브러리에는 PIL이 필요합니다.
python generateDrawableXML.py [img_path]
generateDrawableXML.py #! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from PIL import Image
def getCenterList(_list, order=1):
if order > 0:
return [i for (i, x) in enumerate(_list) if x == max(_list)]
else:
return [i for (i, x) in enumerate(_list) if x == min(_list)]
def getHexColor(rgb):
return '#FF' + getHexStr(rgb[0]) + getHexStr(rgb[1]) + getHexStr(rgb[2])
def getHexStr(color):
hexStr = hex(color)[2:].upper()
return hexStr if len(hexStr) == 2 else '0' + hexStr
def main(path):
img = Image.open(path)
img = img.resize((1, img.size[1]))
img = img.convert("RGB")
rgbs = list(img.getdata())
height = len(rgbs)
startRGB = rgbs[0]
endRGB = rgbs[len(rgbs) - 1]
centerRGB = None
centerIndex = 0
rs, gs, bs = [], [], []
for rgb in rgbs:
rs.append(rgb[0])
gs.append(rgb[1])
bs.append(rgb[2])
for i in [-1, 1]:
centerSet = set(getCenterList(rs, i)) & set(getCenterList(gs, i)) & set(getCenterList(bs, i))
if len(centerSet) == 0: continue
index = list(centerSet)[0]
if index != 0 and index != (height - 1):
centerRGB = rgbs[index]
centerIndex = index
centerStr = ""
if centerRGB:
centerStr = """
android:centerColor="%s"
android:centerY="%s"
""" % (getHexColor(centerRGB), round(float(centerIndex) / float(height - 1), 1))
print """
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="270"
android:type="linear"
android:startColor="%s"
android:endColor="%s"%s
/>
</shape>""" % (getHexColor(startRGB), getHexColor(endRGB), centerStr)
if __name__ == '__main__':
argvs = sys.argv
if len(argvs) != 2:
print("python " + argvs[0] + " [img_path]")
else:
main(argvs[1])
그러면 다음 XML이 생성됩니다. <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="270"
android:type="linear"
android:startColor="#FF330F55"
android:endColor="#FFC45D19"
/>
</shape>
또한 센터 요소가 있는 이미지도 가능하다. <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="270"
android:type="linear"
android:startColor="#FFFFC081"
android:endColor="#FFFFA349"
android:centerColor="#FFFF8101"
android:centerY="0.6"
/>
</shape>
※ 가로 및 원형 그라데이션은 지원되지 않습니다.
Reference
이 문제에 관하여(그래디언트 이미지에서 Android XML 자동 생성), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/ayakix/items/86a651fedd9f0b2d4acd텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)