본문 바로가기
User Guide

Add Multi-Density Images with SVGs (15)

by 각종 잡상식 지식 모음 2016. 6. 2.
반응형

SVG로 복수-밀도 이미지 추가하기 Add Multi-Density Images with SVGs

안드로이드 스튜디오에는, 프로젝트에 드로어블 자원으로, 물질 아이콘을 추가하고 확장가능벡터그래픽(SVG) 파일을 추가할 수 있는. 벡터 자산 스튜디오라는 도구가 포함되어 있습니다.
같은 파일을 이미지 품질의 손실없이 다른 화면 밀도에 대하여 크기를 조정할 수 있기 때문에, 비트맵 대신 SVGs을 사용하면 APK의 크기를 줄일 수 있습니다.
SVG 파일을 지원하지 않는 안드로이드의 이전 버전에 대하여, 벡터 자산 스튜디오는 각 화면 밀도에 대해 서로 다른 비트 맵 크기로 SVG를 내보낼 수 있습니다.
Android Studio includes a tool called Vector Asset Studio that helps you add material icons and import Scalable Vector Graphic (SVG) files into your project as a drawable resource. Using SVGs instead of bitmaps reduces the size of your APK because the same file can be resized for different screen densities without loss of image quality. For older version of Android that don't support SVG files, Vector Asset Studio can export your SVG into different bitmap sizes for each screen density.

About Vector Asset Studio


벡터 자산 스튜디오는 이미지를 설명하는 XML 파일로 프로젝트에 벡터 그래픽을 추가합니다.
하나의 XML 파일을 만들어 관리하면 다양한 해상도에서 여러 래스터 그래픽을 업데이트하는 것보다 쉬울 수 있습니다.

Vector Asset Studio adds a vector graphic to the project as an XML file that describes the image. Maintaining one XML file can be easier than updating multiple raster graphics at various resolutions.

안드로이드4.4 (API레벨 20)과 이전 버전은 벡터 드로어블을 지원하지 않습니다.
최소 API 레벨이 이러한 API 레벨 중 하나에 설정되어 있는 경우, 벡터 자산 스튜디오를 사용할 때, 2가지 옵션이 있습니다:
이동식 네트워크 그래픽(PNG) 파일(기본)를 생성하거나 지원 라이브러리를 사용
Android 4.4 (API level 20) and lower doesn't support vector drawables. If your minimum API level is set at one of these API levels, you have two options when using Vector Asset Studio: generate Portable Network Graphic (PNG) files (the default) or use the Support Library.

이전 버전과의 호환성을 위해 벡터 자산 스튜디오는 벡터 드로어블의 래스터 이미지를 생성합니다. 
벡터 및 래스터 드로어블은 APK로 함께 포장됩니다.
자바 코드에서 D
rawable로 또는 XML 코드에서 @drawable로 벡터 자산을 참조할 수 있습니다;
app이 실행될 때, API 레벨에 따라 해당 벡터 또는 래스터 이미지가 자동적으로 디스플레이됩니다.
For backward-compatibility, Vector Asset Studio generates raster images of the vector drawable. The vector and raster drawables are packaged together in the APK. You can refer to vector assets as Drawable in Java code or @drawable in XML code; when your app runs, the corresponding vector or raster image displays automatically depending on the API level.

안드로이드 지원 라이브러리 23.2 이상을 대신 사용하려면 build.gradlefile에 몇 가지 statements를 추가해야합니다.
이 기술은 벡터 드로어블 만을 사용합니다.
To instead use Android Support Library 23.2 or higher, you must add some statements to your build.gradlefile. This technique uses vector drawables only.

Supported vector graphic types

The Google material design specification provides material icons that you can use in your Android apps. Vector Asset Studio helps you choose, import, and size material icons, as well as define opacity and the Right-to-Left (RTL) mirroring setting.

Vector Asset Studio also helps you to import your own SVG files. SVG is an XML-based open standard of the World Wide Web Consortium (W3C). Vector Asset Studio supports the essential standard, but not all features. When you specify an SVG file, Vector Asset Studio gives immediate feedback about whether the graphics code is supported or not. If the SVG code is supported, it converts the file into an XML file containing VectorDrawable code.

For Android 5.0 (API level 21) and higher, you can use the AnimatedVectorDrawable class to animate the properties of VectorDrawable. For more information, see Animate Vector Drawables.

Considerations for SVG files

A vector drawable is appropriate for simple icons. The material icons provide good examples of the types of images that work well as vector drawables in an app. In contrast, many app launch icons do have many details, so they work better as raster images.

The initial loading of a vector graphic can cost more CPU cycles than the corresponding raster image. Afterward, memory use and performance are similar between the two. We recommend that you limit a vector image to a maximum of 200 x 200 dp; otherwise, it can take too long to draw.

Although vector drawables do support one or more colors, in many cases it makes sense to color icons black (android:fillColor="#FF000000"). Using this approach, you can add a tint to the vector drawable that you placed in a layout, and the icon color changes to the tint color. If the icon color isn't black, the icon color might instead blend with the tint color.

Vector drawable backward-compatibility solutions

The following table summarizes the two techniques you can use for backward-compatibility with Android 4.4 (API level 20) and lower:

TechniqueDrawables in APKVectorDrawable XML ElementsAndroid Plugin for GradleBuild FlagsApp Code
PNG generationVector and rasterSubset supported1.5.0 or higherDefaultVariety of coding techniques supported
Support Library 23.2 or higherVectorFull support2.0 or higherSupport Library statements requiredSubset of coding techniques supported

Using vector graphics can produce a smaller APK, but the initial loading of vector graphics can take longer.

PNG generation

Android 5.0 (API level 21) and higher provides vector drawable support. If your app has a minimum API level that is lower, Vector Asset Studio adds the vector drawable file to your project; also, at build time, Gradle creates PNG raster images at various resolutions. Gradle generates the PNG densities specified by the Domain Specific Language (DSL) generatedDensities property in a build.gradle file. To generate PNGs, the build system requires Android Plugin for Gradle 1.5.0 or higher.

For Android 5.0 (API level 21) and higher, Vector Asset Studio supports all of the VectorDrawable elements. For backward compatibility with Android 4.4 (API level 20) and lower, Vector Asset Studio supports the following XML elements:

<vector>

  • android:width
  • android:height
  • android:viewportWidth
  • android:viewportHeight
  • android:alpha

<group>

  • android:rotation
  • android:pivotX
  • android:pivotY
  • android:scaleX
  • android:scaleY
  • android:translateX
  • android:translateY

<path>

  • android:pathData
  • android:fillColor
  • android:strokeColor
  • android:strokeWidth
  • android:strokeAlpha
  • android:fillAlpha
  • android:strokeLineCap
  • android:strokeLineJoin
  • android:strokeMiterLimit

Only Android 5.0 (API level 21) and higher supports dynamic attributes, for example, android:fillColor="?android:attr/colorControlNormal".

You can change the XML code that Vector Asset Studio generates, although it’s not a best practice. Changing the values in the code should not cause any issues, as long as they’re valid and static. If you want to add XML elements, you need to make sure that they’re supported based on your minimum API level.

Support Library

This technique requires Android Support Library 23.2 or higher and Android Plugin for Gradle 2.0 or higher, and uses vector drawables only. Before using Vector Asset Studio, you must add a statement to your build.gradle file:

android {
  defaultConfig
{
    vectorDrawables
.useSupportLibrary = true
 
}
}

dependencies
{
  compile
'com.android.support:appcompat-v7:23.2.0'
}
 

You must also use coding techniques that are compatible with the Support Library. For more information, see Android Support Library 23.2.

Running Vector Asset Studio


To start Vector Asset Studio:

  1. In Android Studio, open an Android app project.
  2. In the Project window, select the Android view.
  3. Right-click the res folder and select New > Vector Asset.
  4. Some other project views and folders have this menu item as well.

    Vector Asset Studio appears.

  5. If a Need newer Android plugin for Gradle dialog appears instead, correct your Gradle version as follows:
    1. Select File > Project Structure.
    2. In the Project Structure dialog, select Project.
    3. In the Android Plugin Version field, change the Android Plugin for Gradle version to 1.5.0 or higher, and click OK.
    4. Gradle syncs the project.

    5. In the Android view of the Project window, right-click the res folder and select New > Vector Asset.
    6. Vector Asset Studio appears.

  6. Continue with Importing a Vector Graphic.

Importing a Vector Graphic


Vector Asset Studio helps you to import a vector graphics file into your app project. Follow one of the following procedures:

Adding a material icon

After you open Vector Asset Studio, you can add a material icon as follows:

  1. In Vector Asset Studio, select Material Icon.
  2. Click Choose.
  3. Select a material icon and click OK.
  4. The icon appears in the Vector Drawable Preview.

  5. Optionally change the resource name, size, opacity, and Right-To-Left (RTL) mirroring setting:
    • Resource name - Type a new name if you don’t want to use the default name. Vector Asset Studio automatically creates a unique name (adds a number to the end of the name) if that resource name already exists in the project. The name can contain lowercase characters, underscores, and digits only.
    • Override default size from material design - Select this option if you want to adjust the size of the image. When you type a new size, the change appears in the preview area.
    • The default is 24 x 24 dp, which is defined in the material design specification. Deselect the checkbox to return to the default.

    • Opacity - Use the slider to adjust the opacity of the image. The change appears in the preview area.
    • Enable auto mirroring for RTL layout - Select this option if you want a mirror image to display when the layout is right to left, instead of left to right. For example, some languages are read right to left; if you have an arrow icon, you might want to display a mirror image of it in this case. Note that if you’re working with an older project, you might also need to add android:supportsRtl="true" to your app manifest. Auto-mirroring is supported on Android 5.0 (API level 21) and higher, and the Support Library.
  6. Click Next.
  7. Optionally change the module and resource directory:
    • Target Module - Select a module in the project where you want to add the resource. For more information, see Add an App Module.
    • Res Directory - Select the resource source set where you want to add the vector asset: src/main/ressrc/debug/ressrc/release/res, or a user-defined source set. The main source set applies to all build variants, including debug and release. The debug and release source sets override the main source set and apply to one version of a build. The debug source set is for debugging only. To define a new source set, select File > Project Structure > app > Build Types. For example, you could define a beta source set and create a version of an icon that includes the text "BETA” in the bottom right corner. For more information, see Configure Build Variants.

    The Output Directories area displays the vector image and the directory where it will appear.

  8. Click Finish.
  9. Vector Asset Studio adds an XML file defining the vector drawable to the project in the app/src/main/res/drawable/ folder. From the Android viewof the Project window, you can view the generated vector XML file in the drawable folder.

  10. Build the project.
  11. If the minimum API level is Android 4.4 (API level 20) and lower, and you haven't enabled the Support Library technique, Vector Asset Studio generates PNG files. From the Project view of the Project window, you can view the generated PNG and XML files in theapp/build/generated/res/pngs/debug/ folder.

    You should not edit these generated raster files, but instead work with the vector XML file. The build system regenerates the raster files automatically when needed so you don’t need to maintain them.

Importing a Scalable Vector Graphic (SVG)

After you open Vector Asset Studio, you can import an SVG file as follows:

  1. In Vector Asset Studio, select Local SVG file.
  2. The file must be on a local drive. If it’s located on the network, for example, you need to download it to a local drive first.

  3. Specify an Image file by clicking  .
  4. The image appears in the Vector Drawable Preview.

    However, if the SVG file contains unsupported features, an error appears at the bottom left of Vector Asset Studio, as shown in the following figure.

    In this case, you can’t use Vector Asset Studio to add the graphics file. Click More to view the errors. For a list of supported elements, see Vector Drawable Backward-Compatibility Solutions.

  5. Optionally change the resource name, size, opacity, and Right-To-Left (RTL) mirroring setting:
    • Resource name - Type a new name if you don’t want to use the default name. Vector Asset Studio automatically creates a unique name (adds a number to the end of the name) if that resource name already exists in the project. The name can contain lowercase characters, underscores, and digits only.
    • Override default size from material design - Select this option if you want to adjust the size of the image. After you select it, the size changes to the size of the image itself. Whenever you change the size, the change appears in the preview area.
    • The default is 24 x 24 dp, which is defined in the material design specification. Deselect the checkbox to return to the default.

    • Opacity - Use the slider to adjust the opacity of the image. The change appears in the preview area.
    • Enable auto mirroring for RTL layout - Select this option if you want a mirror image to display when the layout is right to left, instead of left to right. For example, some languages are read right to left; if you have an arrow icon, you might want to display a mirror image of it in this case. Note that if you’re working with an older project, you might need to add android:supportsRtl="true" to your app manifest. Auto-mirroring is supported on Android 5.0 (API level 21) and higher, and the Support Library.
  6. Click Next.
  7. Optionally change the module and resource directory:
    • Target Module - Select a module in the project where you want to add the resource. For more information, see Add an App Module.
    • Res Directory - Select the resource source set where you want to add the vector asset: src/main/ressrc/debug/ressrc/release/res, or a user-defined source set. The main source set applies to all build variants, including debug and release. The debug and release source sets override the main source set and apply to one version of a build. The debug source set is for debugging only. To define a new source set, select File > Project Structure > app > Build Types. For example, you could define a beta source set and create a version of an icon that includes the text "BETA” in the bottom right corner. For more information, see Configure Build Variants.

    The Output Directories area displays the vector image and the directory where it will appear.

  8. Click Finish.
  9. Vector Asset Studio adds an XML file defining the vector drawable to the project in the app/src/main/res/drawable/ folder. From the Android viewof the Project window, you can view the generated vector XML file in the drawable folder.

  10. Build the project.
  11. If the minimum API level is Android 4.4 (API level 20) and lower, and you haven't enabled the Support Library technique, Vector Asset Studio generates PNG files. From the Project view of the Project window, you can view the generated PNG and XML files in theapp/build/generated/res/pngs/debug/ folder.

    You should not edit these generated raster files, but instead work with the vector XML file. The build system regenerates the raster files automatically when needed so you don’t need to maintain them.

Adding a Vector Drawable to a Layout


In a layout file, you can set any icon-related widget, such as ImageButtonImageView, and so on, to point to a vector asset. For example, the following layout shows a vector asset displayed on a button:

To display a vector asset on a widget, as shown in the figure:

  1. Open a project and import a vector asset.
  2. In the Android view of the Project window, double-click a layout XML file, such as content_main.xml.
  3. Click the Design tab to display the Layout Editor.
  4. Drag the ImageButton widget from the Palette window onto the Layout Editor.
  5. In the Properties window, locate the src property of the ImageButton instance and click  .
  6. In the Resources dialog, select the Project tab, navigate to the Drawable folder, and select a vector asset. Click OK.
  7. The vector asset appears on the ImageButton in the layout.

  8. To change the color of the image to the accent color defined in the theme, locate the tint property in the Properties window and click  .
  9. In the Resources dialog, select the Project tab, navigate to the Color folder, and select colorAccent. Click OK.
  10. The color of the image changes to the accent color in the layout.

If you're not using the Support Library technique, the ImageButton code should be similar to the following:

<ImageButton
 
android:id="@+id/imageButton"
 
android:src="@drawable/ic_build_24dp"
 
android:tint="@color/colorAccent"
 
android:layout_width="wrap_content"
 
android:layout_height="wrap_content"
 
android:layout_below="@+id/textView2"
 
android:layout_marginTop="168dp" />

Referring to a Vector Drawable in Code


You can normally refer to a vector drawable resource in a generic way in your code, and when your app runs, the corresponding vector or raster image displays automatically depending on the API level:

  • In most cases, you can refer to vector assets as @drawable in XML code or Drawable in Java code.
  • For example, the following layout XML code applies the image to a view:

    <ImageView
       
    android:layout_height="wrap_content"
       
    android:layout_width="wrap_content"
       
    android:src="@drawable/myimage" />

    The following Java code retrieves the image as a Drawable:

    Resources res = getResources();
    Drawable drawable = res.getDrawable(R.drawable.myimage);
  • Occasionally, you might need to typecast the drawable resource to its exact class, such as when you need to use specific features of theVectorDrawable class. To do so, you could use Java code such as the following:
  • if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
       
    VectorDrawable vectorDrawable =  (VectorDrawable) drawable;
    } else {
       
    BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
    }

For the Support Library technique, you must use coding techniques that are compatible with the Support Library. For more information, see Android Support Library 23.2.

Modifying XML Code Generated by Vector Asset Studio


You can modify the vector asset XML code, but not the PNGs and corresponding XML code generated at build time. However, we don't recommended it.

When using the PNG generation technique, Vector Asset Studio makes sure that the vector drawable and the PNGs match, and that the manifest contains the proper code. If you add code that's not supported on Android 4.4 (API level 20) and lower, your vector and PNG images might differ. You also need to make sure that the manifest contains the code to support your changes.

To modify the vector XML file when you're not using the Support Library technique:

  1. In the Project window, double-click the generated vector XML file in the drawable folder.
  2. The XML file appears in the editor and Preview windows.

  3. Edit the XML code based on what’s supported by the minimum API level:
    • Android 5.0 (API level 21) and higher - Vector Asset Studio supports all of the Drawable and VectorDrawable elements. You can add XML elements and change values.
    • Android 4.4 (API level 20) and lower - Vector Asset Studio supports all of the Drawable elements and a subset of the VectorDrawable elements. See Vector Drawable Backward-Compatibility Solutions for a list. You can change values in the generated code and add XML elements that are supported. Dynamic attributes aren't supported.

    For example, if you didn’t select the RTL option in Vector Asset Studio but realize you now need it, you can add the autoMirrored attribute later. To view the RTL version, select Preview Right-to-Left Layout in the  menu of the Preview window. (Select None to remove the RTL preview.)

    Note: If you’re working with an older project, you might need to add android:supportsRtl="true" to your app manifest. Also, becauseautoMirrored is a dynamic attribute, it's supported on Android 5.0 (API level 21) and higher only.

  4. Build the project and check that the vector and raster images look the same.
  5. Remember that the generated PNGs could display differently in the Preview window than in the app due to different rendering engines and any changes made to the vector drawable before a build. If you add code to the vector XML file created by Vector Asset Studio, any features unsupported in Android 4.4 (API level 20) and lower don't appear in the generated PNG files. As a result, when you add code, you should always check that the generated PNGs match the vector drawable. To do so, you could double-click the PNG in the Project view of the Project window; the left margin of the code editor also displays the PNG image when your code refers to the drawable.

Deleting a Vector Asset from a Project


To remove a vector asset from a project:

  1. In the Project window, delete the generated vector XML file by selecting the file and pressing the Delete key (or select Edit > Delete).
  2. The Safe Delete dialog appears.

  3. Optionally select options to find where the file is used in the project, and click OK.
  4. Android Studio deletes the file from the project and the drive. However, if you chose to search for places in the project where the file is used and some usages are found, you can view them and decide whether to delete the file.

  5. Select Build > Clean Project.
  6. Any auto-generated PNG and XML files corresponding to the deleted vector asset are removed from the project and the drive.

Delivering an App Containing Vector Drawables


If you used the Support Library technique or your minimum API level is Android 5.0 (API level 21) or higher, your APK will contain the vector images that you added with Vector Asset Studio. These APKs will be smaller than if the vector images were converted to PNGs.

When your minimum API level includes Android 4.4 (API level 20) or lower, and you have corresponding vector and raster images in your project, you have two options for delivering your APK files:

  • Create one APK that includes both the vector images and the corresponding raster representations. This solution is the simplest to implement.
  • Create separate APKs for different API levels. When you don’t include the corresponding raster images in the APK for Android 5.0 (API level 21) and higher, the APK can be much smaller in size. For more information, see Multiple APK Support.


반응형

댓글