Nice programing

Android에서 SVG 아이콘을 사용하는 모범 사례는 무엇입니까?

nicepro 2020. 10. 26. 21:03
반응형

Android에서 SVG 아이콘을 사용하는 모범 사례는 무엇입니까?


첫 번째 Android 네이티브 (브라우저 기반이 아님) 앱 을 만들려고하고 아이콘 생성 / 프로비저닝과 관련된 몇 가지 좋은 방법을 찾고 있습니다. 여러 장치 / 해상도를 지원해야하기 때문에 SVG를 사용하여 만드는 것이 가장 좋다고 생각했습니다. 적어도이 lib : http://code.google.com/p/svg-android/ 는 Android에서 SVG에 대한 지원을 제공 할 것을 약속합니다.

지금까지 장치에서 SVG 아이콘을 렌더링하는 수단으로이 라이브러리 나 다른 라이브러리를 사용하는 방법을 설명하는 리소스를 찾지 못했기 때문에 사용하기를 조금 꺼립니다. 지금까지 내가 본 것 중 최고는 SVG를 다양한 해상도의 png 기반 아이콘을 미리 렌더링하기위한 소스 형식으로 사용하는 것입니다.

그래서 내 질문은 다음과 같습니다. SVG 아이콘은 png 사전 렌더링 단계없이 장치에서 직접 사용할 수있는 좋은 옵션입니까 (전혀 작동합니까), 왜 아무도이 방법을 사용하지 않는 것 같습니까?


Lollipop보다 오래된 Android의 경우 Android에서 SVG에 대한 모범 사례는 도구를 사용하여 원하는 크기로 SVG를 PNG로 변환하는 것입니다. Android에 대한 기존 SVG 지원은 사용자가 무엇을 포괄적으로 지원하지 않습니다. SVG 파일에서 찾을 가능성이 높고, 그렇더라도 지원이 OS에 내장되어 있지 않으므로 아이콘에 직접 사용하는 것은 확실히 없습니다.

Lollipop (API 21)부터 Android에서 SVG 아이콘을 사용하기위한 모범 사례는 무엇입니까?를 참조하십시오 . . 이것을 지적 해 주신 @MarkWhitaker @AustynMahoney에게 감사드립니다.


Lollipop (API 21)부터 Android는 벡터 그래픽을 기반으로 드로어 블을 정의하기 위해 VectorDrawable 클래스를 정의합니다. Android Studio 1.4는 SVG 가져 오기 기능과 API 20 및 이전 버전의 빌드시 VectorDrawable 아이콘의 PNG 버전을 생성하는 새로운 Gradle 플러그인을 포함하여 더 쉽게 작업 할 수 있도록 "Vector Asset Studio"추가합니다 . SVG를 VectorDrawables로 변환하는 타사 도구 도 있습니다 . 벡터 드로어 블은 XML로 정의 할 수 있지만 파일 형식은 SVG가 아니며 모든 SVG 파일을 성공적으로 변환 할 수는 없습니다. 아이콘과 같은 단순한 그래픽이 정상적으로 작동합니다.

여전히 PNG를 직접 생성해야하는 경우 다양한 해상도로 아이콘을 생성해야합니다 . 이러한 PNG를 쉽게 생성하기 위해 아이콘을 SVG로 디자인 한 다음 무료 및 크로스 플랫폼 인 Inkscape사용하여 다양한 크기로 내 보냅니다 . 아이콘 미리보기보기 (아래 참조)를 포함하여 아이콘 디자인을위한 몇 가지 멋진 기능이 있으며 멋진 선명한 PNG를 생성합니다.

여기에 이미지 설명 입력


이것이 우리가 SVG 파일을 여러 해상도로 변환하는 데 사용하는 것입니다. 예를 들어 시작 아이콘을 생성하려면 다음을 수행하십시오.svg2png -w48 icon.svg

#!/bin/bash -e
# Transforms a SVG into a PNG for each platform
# Sizes extracted from
# http://developer.android.com/design/style/iconography.html

[ -z $2 ] && echo -e "ERROR: filename and one dimension (-w or -h) is required, for example:\nsvg2png -w48 icon.svg\n" && exit 1;
FILENAME=$2
DEST_FILENAME=`echo $2 | sed s/\.svg/\.png/`
FLAG=`echo $1 | cut -c1-2`
ORIGINAL_VALUE=`echo $1 | cut -c3-`

if [ "$FLAG" != "-w" ] && [ "$FLAG" != "-h" ]; then
    echo "Unknown parameter: $FLAG" 
    exit 1
fi

# PARAMETERS: {multiplier} {destination folder}
function export {
  VALUE=$(echo "scale=0; $ORIGINAL_VALUE*$1" | bc -l)
  CMD="inkscape $FLAG$VALUE --export-background-opacity=0 --export-png=src/main/res/$2/$DEST_FILENAME src/main/svg/$FILENAME > /dev/null"
  echo $CMD
  eval $CMD
} 

export 1 drawable-mdpi
export 1.5 drawable-hdpi
export 2 drawable-xhdpi
export 3 drawable-xxhdpi
export 4 drawable-xxxhdpi

모두 좋은 소식입니다! 안드로이드 지원 라이브러리 23.2 부터 우리는 API 레벨 7로 돌아갈 때까지 svg-s를 사용할 수 있습니다 !

Lollipop (API 21)까지만 하위 호환성을 유지하려면 Mark Whitaker의 답변을 확인하십시오 .하지만 아래로 이동하려면 build.gradle에 다음 줄을 추가해야합니다.

// Gradle Plugin 2.0+ (if you using older version check the library announcement link)
android {  
    defaultConfig {  
        vectorDrawables.useSupportLibrary = true  
    }  
}  

또한 다음 사항에 유의하십시오.

  • 대신 ImageViews android:src에서 app:srcCompat속성 을 사용해야합니다 .
  • StateListDrawables 또는 다른 xml 드로어 블에서 svg-s를 사용할 수 없으며 대신 프로그래밍 방식으로 만들 수 있습니다.
  • android:background속성이나 View.setBackgroundResource()함수를 사용할 수 없으며 View.setBackground()대신 사용하십시오 .
  • 알림의 경우 svg-s를 사용할 수 없습니다.

nacho-coloma 의 답변이 도움이 되었기 때문에 그의 훌륭한 대본을 가져와 매일 사용하기 약간 더 쉽게 만들었습니다.

먼저:

  1. 디렉토리 drawable-svg옆에 디렉토리를 만듭니다 res.
  2. svg 파일과이 스크립트를 drawable-svg.
  3. 스크립트를 실행 가능하게 만드십시오.
  4. 그것을 실행하십시오. Ubuntu에서는 Nautilus에서 간단히 두 번 클릭하여 터미널에서 실행할 수 있습니다.

나중에 새 svg 파일을 얻을 때 :

  1. 새 svg 파일을 drawable-svg넣고 스크립트를 다시 실행하십시오.

기본적으로 원하는 작업을 수행합니다. 모든 svg 파일을 png 파일로 크기를 조정 ../res/drawable-mdpi하고 ../res/drawable-hdpi.

스크립트는 두 개의 매개 변수를 사용합니다.

  1. 확장 할 svg 파일 패턴, 기본값 : *.svg
  2. put에 대한 기본 디렉토리, 기본값 ../res/(즉 res, 위에서 언급 한 설정이있는 디렉토리).

다음과 같이 현재 디렉토리에서 단일 svg를 png로 확장하여 실험 할 수 있습니다.

$ ./svg2png test.svg .

또는 단순히 모든 이미지를 처리합니다.

$ ./svg2png

drawable-svgres 디렉토리 안에 넣을 수 있다고 생각 하지만 최종 APK에 포함되는 내용은 살펴 보지 않았습니다. 또한 내 svg 파일에는 -Android가 싫어하는 이름이 있으며 내 스크립트는 png 파일의 이름을 Android에서 유효한 이름으로 변경합니다.

나는 Inkscape보다 약간 더 표준적인 변환을 위해 ImageMagick을 사용하고 있습니다. 두 방법 모두 참조를 위해 스크립트에 포함되어 있습니다.

다음은 스크립트입니다.

#!/bin/bash

scalesvg ()
{
    svgfile="$1"
    pngdir="$2"
    pngscale="$3"
    qualifier="$4"

    svgwidthxheight=$(identify "$svgfile" | cut -d ' ' -f 3)
    svgwidth=${svgwidthxheight%x*}
    svgheight=${svgwidthxheight#*x}

    pngfile="$(basename $svgfile)" # Strip path.
    pngfile="${pngfile/.svg/.png}" # Replace extension.
    pngfile="${pngfile/[^A-Za-z0-9._]/_}" # Replace invalid characters.
    pngfile="$pngdir/$qualifier/$pngfile" # Prepend output path.

    if [ ! -d $(dirname "$pngfile") ]; then
        echo "WARNING: Output directory does not exist: $(dirname "$pngfile")"
        #echo "Exiting"
        #exit 1
        echo "Outputting here instead: $pngfile"
        pngfile="$qualifier-${svgfile/.svg/.png}"
    fi

    pngwidth=$(echo "scale=0; $svgwidth*$pngscale" | bc -l)
    pngheight=$(echo "scale=0; $svgheight*$pngscale" | bc -l)
    pngdensity=$(echo "scale=0; 72*$pngscale" | bc -l) # 72 is default, 

    echo "$svgfile ${svgwidth}×${svgheight}px -> $pngfile ${pngwidth}×${pngheight}px @ $pngdensity dpi"

    convert -background transparent -density $pngdensity "$svgfile" "$pngfile"
    #inkscape -w${pngwidth} --export-background-opacity=0 --export-png="$pngfile" "$svgfile" > /dev/null
    #convert "$svgfile" -background transparent -scale ${pngwidth}x${pngheight} "$pngfile"
}



svgfiles="$1"
svgfiles="${svgfiles:=*.svg}" # Default to input all *.svg in current dir.

pngdir="$2"
pngdir="${pngdir:=../res}" # Default to place output pngs to ../res, ie. ../res/drawable-hdpi etc.

for svgfile in $svgfiles; do
    echo "Scaling $svgfile ..."
    scalesvg "$svgfile" "$pngdir" 0.75 drawable-ldpi
    scalesvg "$svgfile" "$pngdir" 1    drawable-mdpi
    scalesvg "$svgfile" "$pngdir" 1.5  drawable-hdpi
    scalesvg "$svgfile" "$pngdir" 2    drawable-xhdpi
    scalesvg "$svgfile" "$pngdir" 3    drawable-xxhdpi
    scalesvg "$svgfile" "$pngdir" 4    drawable-xxxhdpi
done

echo -n "Done."
read # I've made it wait for Enter -- convenient when run from Nautilus.

또 다른 옵션은 SVG 자산을 TTF 글꼴 유형으로 변환하는 것입니다. 앱에 글꼴을 포함하고 그렇게 사용하십시오. 이것은 단색의 단순한 모양에 대한 트릭을 수행합니다.

몇 가지 무료 변환 도구가 있습니다.


Android 지원 라이브러리 23.2 지원 벡터 드로어 블 및 애니메이션 벡터 드로어 블

  1. vectorDrawables.useSupportLibrary = truebuild.gradle 파일에 추가 하십시오.
  2. 사용 app:srcCompat="@drawable/ic_add"대신에 android:src="..."또는 setImageResource()당신의 이미지 뷰에 대한

http://android-developers.blogspot.sk/2016/02/android-support-library-232.html


SVG icons are not a good option to use directly on a device if they need to be scaled to many different sizes, which is usually why you'd want to use vector format in the first place. A large icon will never scale down gracefully because, well, computer displays are made out of pixels. So the lines of the vector image may get aligned "in between pixels", creating a blurry border. Moreover, large icons need more details than small icons, which need very few details. A detailed icon does not look good in very small size, and a simple icon does not look good when scaled into very large size. I recently read an excellent article on this by a professional UI designer: About those vector icons.


I've just posted a script for generating all the platform icons for PhoneGap apps that may be of value. Yet to add code for generating screens.


I've just started using Victor, an open source library by Trello, to convert SVG files to PNG files of the various required resolutions during build time.

PROS

  • You won't have to run a script or tool to create various PNG files every time you change or add an icon. (You do need to hit Rebuild in Android Studio when you've added a new svg file or renamed an existing one)
  • No PNG's in your source, so there's less clutter.

CONS

  • The only downside I've seen so far is that Android Studio doesn't yet recognize generated resources in XML, so you'll get some red warnings in your XML files and you don't have autocomplete for your SVG based drawables. It builds fine though, and this issue should be fixed in a future version of Android Studio.

If you use SVG generated by http://materialdesignicons.com/ be sure to either download the whole file, or copy from the 'SVG File'-tab when choosing 'View SVG'


svg is awesome. who want use svg:

right click on drawable "new/Vector Asset" choose "material icon" for default icons and "locale SVG file" for your file in your computer hard drive and in "resource name" type name for svg file then click on "next" button and "finish"

and you can use that in drawable. fillcolor must be hard code.

simple example

navigation_toggle.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#FFFFFF"
        android:pathData="M3,18h18v-2H3v2zm0,-5h18v-2H3v2zm0,-7v2h18V6H3z"/>
</vector>

I've never had much luck running Linux shell scripts in Cygwin on Windows. So here is a batch file that does what Nacho Coloma's bash script does. One small difference, is that this batch file requires both an input and an output file name, as in "svg2png -w24 input.svg output.png".

프로젝트의 src / main 디렉토리에 "svg"폴더를 설정하고 Stephan의 지침에 따라 SVG 파일과이 배치 파일을 해당 폴더에 복사합니다. svg 폴더에서 배치 파일을 실행합니다. 32 비트 Windows를 사용하는 경우 "Program Files (x86)"를 사용하려면 경로를 Inkscape로 변경해야합니다.

@echo off
echo Convert an SVG file to a PNG resource file with multiple resolutions.

rem Check the arguments
set temp=%1
set switch=%temp:~0,2%
set pixels=%temp:~2%
if not "%switch%"=="-w" (
if not "%switch%"=="-h" (
echo Error:  Invalid image width or height switch.  Use -w or -h, with target image size in dp appended.
goto :error
))
echo %pixels%| findstr /r /c:"^[1-9][0-9]*$" >nul
if errorlevel 1 (
echo Error:  Invalid numeric image size.  Image size must be a positive integer.
goto :error
)
if "%3"=="" (
echo Error:  Not enough arguments.
goto :error
)
if not "%4"=="" (
echo Error:  Too many arguments.
goto :error
)

call :export %1 %2 %3 mdpi
call :export %1 %2 %3 hdpi
call :export %1 %2 %3 xhdpi
call :export %1 %2 %3 xxhdpi
call :export %1 %2 %3 xxxhdpi
exit /b

:export
rem parameters: <width/height> <input-file> <output-file> <density>

set temp=%1
set switch=%temp:~0,2%
set pixels=%temp:~2%

if %4==mdpi set /a size=%pixels%
if %4==hdpi set /a size=%pixels%*3/2
if %4==xhdpi set /a size=%pixels%*2
if %4==xxhdpi set /a size=%pixels%*3
if %4==xxxhdpi set /a size=%pixels%*4

echo %size% pixels ../res/drawable-%4/%3
"C:\Program Files\Inkscape\inkscape.exe" %switch%%size% --export-background-opacity=0 --export-png=../res/drawable-%4/%3 %2
exit /b

:error
echo Synopsis: svg2png -w^<width-pixels^>^|-h^<height-pixels^> ^<input-file^> ^<output-file^>
echo Example:  svg2png -w24 "wifi white.svg" wifi_connect_24dp.png
exit /b

참고 URL : https://stackoverflow.com/questions/9647770/what-are-best-practices-for-using-svg-icons-on-android

반응형