SoFunction
Updated on 2025-04-21

Detailed explanation of XML graphics files in the Android Drawable directory

1. Basic XML Drawable Type

1. Vector graphics (VectorDrawable)

File locationres/drawable/orres/drawable-anydpi/

<vector xmlns:andro
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24.0"
    android:viewportHeight="24.0">
    
    <path
        android:fillColor="#FF000000"
        android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2z"/>
</vector>

Key attributes

  • width/height: Intrinsic dimensions of vector illustration
  • viewportWidth/viewportHeight: The logical size of the canvas
  • pathData: Define the path data of the shape (SVG format)
  • fillColor: Fill color
  • strokeColor: Stroke color
  • strokeWidth: Stroke width

advantage

  • Arbitrary scaling without distortion
  • Small file size
  • Properties can be modified dynamically through code

2. ShapeDrawable

File locationres/drawable/

<shape xmlns:andro
    android:shape="rectangle">
    
    <corners android:radius="8dp" />
    <gradient
        android:angle="45"
        android:startColor="#FF6200EE"
        android:endColor="#FF03DAC5"
        android:type="linear" />
    <stroke
        android:width="2dp"
        android:color="#FFFFFF"
        android:dashWidth="4dp"
        android:dashGap="2dp" />
    <size
        android:width="200dp"
        android:height="100dp" />
</shape>

Shape type

  • rectangle(default): Rectangle
  • oval:oval
  • line: Horizontal line
  • ring: Circular

Detailed explanation of child elements

  • <corners>: Rounded corners
    • radius: Unified rounded radius
    • topLeftRadiusetc.: Each corner is set separately
  • <gradient>: Gradient
    • type: linear (linear)/radial (radial)/sweep (scan)
    • centerX/Y: Gradient center point (0-1)
    • gradientRadius: Radial gradient radius
  • <stroke>: Stroke
    • dashWidth: The length of the dotted segment
    • dashGap: Dotted line interval
  • <solid>: Solid color filling
  • <padding>: Inner margin
  • <size>: Intrinsic size

3. LayerDrawable

&lt;layer-list xmlns:andro&gt;
    &lt;!-- Bottom shadow --&gt;
    &lt;item android:top="4dp" android:left="4dp"&gt;
        &lt;shape android:shape="rectangle"&gt;
            &lt;solid android:color="#33000000" /&gt;
            &lt;corners android:radius="8dp" /&gt;
        &lt;/shape&gt;
    &lt;/item&gt;
    
    &lt;!-- Upper content --&gt;
    &lt;item&gt;
        &lt;shape android:shape="rectangle"&gt;
            &lt;solid android:color="#FF6200EE" /&gt;
            &lt;corners android:radius="8dp" /&gt;
        &lt;/shape&gt;
    &lt;/item&gt;
&lt;/layer-list&gt;

Features

  • Stack multiple Drawables in order
  • Each<item>The offset can be set (left/right/top/bottom)
  • Commonly used to create complex combination effects (such as shadowed buttons)

4. StateListDrawable

&lt;selector xmlns:andro&gt;
    &lt;!-- Press status --&gt;
    &lt;item android:state_pressed="true"&gt;
        &lt;shape android:shape="rectangle"&gt;
            &lt;solid android:color="#FF3700B3" /&gt;
            &lt;corners android:radius="8dp" /&gt;
        &lt;/shape&gt;
    &lt;/item&gt;
    
    &lt;!-- Default status --&gt;
    &lt;item&gt;
        &lt;shape android:shape="rectangle"&gt;
            &lt;solid android:color="#FF6200EE" /&gt;
            &lt;corners android:radius="8dp" /&gt;
        &lt;/shape&gt;
    &lt;/item&gt;
&lt;/selector&gt;

Commonly used status attributes

  • state_pressed: Press status
  • state_focused: Get focus
  • state_selected:Selected status
  • state_enabled: Enabled (false means disabled)
  • state_checked: Check status (for CheckBox, etc.)
  • state_activated: Activation status

Important rules

  • Status matching is the first item that meets the criteria
  • The last item should be the default state (no state is specified)

5. Animated Vector (AnimatedVectorDrawable)

composition

  1. Vector (VectorDrawable)
  2. Animation definition (ObjectAnimator)
  3. Animated Vector (AnimatedVectorDrawable)

Example

<!-- res/drawable/avd_heart.xml -->
<animated-vector xmlns:andro
    android:drawable="@drawable/ic_heart">
    
    <target
        android:name="heart"
        android:animation="@animator/heart_beat" />
</animated-vector>
<!-- res/drawable/ic_heart.xml -->
<vector xmlns:andro
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24.0"
    android:viewportHeight="24.0">
    
    <path
        android:name="heart"
        android:pathData="M12,21.35l-1.45,-1.32C5.4,15.36 2,12.28 2,8.5 2,5.42 4.42,3 7.5,3c1.74,0 3.41,0.81 4.5,2.09C13.09,3.81 14.76,3 16.5,3 19.58,3 22,5.42 22,8.5c0,3.78 -3.4,6.86 -8.55,11.54L12,21.35z"
        android:fillColor="#FF0000" />
</vector>
<!-- res/animator/heart_beat.xml -->
<set xmlns:andro>
    <objectAnimator
        android:propertyName="scaleX"
        android:duration="300"
        android:valueFrom="1"
        android:valueTo="1.2"
        android:valueType="floatType"
        android:repeatCount="1"
        android:repeatMode="reverse" />
    
    <objectAnimator
        android:propertyName="scaleY"
        android:duration="300"
        android:valueFrom="1"
        android:valueTo="1.2"
        android:valueType="floatType"
        android:repeatCount="1"
        android:repeatMode="reverse" />
</set>

How to use

ImageButton heartButton = findViewById(.heart_button);
AnimatedVectorDrawableCompat avd = (
    this, .avd_heart);
(avd);
();

2. Advanced skills and applications

1. Dynamically modify the Drawable attribute

// Modify the vector colorVectorDrawableCompat vector = (
    getResources(), .ic_vector, getTheme());
((this, .new_color));

// Modify the shape rounded cornersGradientDrawable shape = (GradientDrawable) ();
(new float[]{
    0, 0,          // Top left    20, 20,        // Top right    40, 40,        // Lower right    0, 0           // Lower left});

2. Topic attribute reference

<shape xmlns:andro>
    <solid android:color="?attr/colorPrimary" />
    <stroke 
        android:width="1dp"
        android:color="?attr/colorPrimaryDark" />
</shape>

3. Vector diagram with zoom

<vector xmlns:andro
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24.0"
    android:viewportHeight="24.0">
    
    <group
        android:name="rotationGroup"
        android:pivotX="12"
        android:pivotY="12"
        android:rotation="0">
        
        <path
            android:name="v"
            android:fillColor="#000000"
            android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2z" />
    </group>
</vector>

4. Complex path combination

<vector xmlns:andro
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24.0"
    android:viewportHeight="24.0">
    
    <path
        android:name="circle"
        android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2z"
        android:fillColor="#4CAF50" />
    
    <path
        android:name="check"
        android:pathData="M9,16.17L4.83,12l-1.42,1.41L9,19 21,7l-1.41,-1.41z"
        android:fillColor="#FFFFFF" />
</vector>

3. Best practices

  1. Naming Specifications

    • Button Status:btn_[Status]_[Color](likebtn_pressed_primary
    • icon:ic_[name](likeic_search
    • background:bg_[Description](likebg_rounded_corner
  2. Performance optimization

    • Preferred vector graphics (simple icon)
    • Complex graphics use WebP format bitmap
    • Avoid using too many levels in StateListDrawable
  3. Adaptation skills

    • Provide alternatives to different topics (drawable-night/
    • Provide compatible versions for different API levels (drawable-v21/
  4. Tool recommendations

    • Vector Asset Studio for Android Studio
    • SVG to VectorDrawable Online Tool
    • Shape Shifter (Advanced Vector Animation Tool)

By using these XML Drawable resources properly, you can create interface elements that are both beautiful and efficient while keeping your application lightweight and maintainable.

Android nine-grid pictures (.) detailed explanation

NinePatch Drawable, file extension is.) is a special PNG image format on the Android platform, which can intelligently stretch pictures without deforming edges and corners.

1. Basic concepts

1. What is a nine-grid picture

The nine-grid picture divides a picture into 9 parts:

  • 4 corners (not stretched)
  • 4 edges (one-way stretch)
  • 1 central area (two-way stretch)

2. File characteristics

  • The file extension must be.
  • A 1-pixel black edge around the picture (defines the stretched area and the content area)
  • The black edge will not be displayed when actually displayed

2. Create a nine-grid picture

1. Create with Android Studio

step

  1. Right-clickres/drawableTable of contents
  2. chooseNew → Image Asset
  3. existAsset TypeSelectNine-Patch
  4. Select the source image and adjust the black edges

2. Create manually

  1. Prepare for ordinary PNG pictures
  2. Add 1 pixel black edge using a picture editing tool such as Photoshop
  3. Mark stretch areas and content areas according to rules
  4. Save as.Format

Detailed explanation of the structure of the 3rd and 9th grid

1. The meaning of four black edges

+---------------------+
| Above:Horizontal stretching area    |
| left:Vertical stretched area    |
| right:Vertical content area    |
| below:Horizontal content area    |
+---------------------+

2. Detailed description

edge effect Marking rules
Above Define the horizontal stretching area Black pixels represent stretchable parts, transparent means non-stretched
left Define the vertical stretched area Black pixels represent stretchable parts, transparent means non-stretched
right Define vertical content area (inside margin) Black pixels represent content boundaries
below Define horizontal content area (inside margin) Black pixels represent content boundaries

IV. Practical examples

1. Sample picture analysis

+-------------------------+
| 1px Black edge marking area          |
|                         |
|    +---------------+    |
|    | Corner area(No stretching) |    |
|    | Side area(Stretch)   |    |
|    | Central area(Stretch) |    |
|    +---------------+    |
|                         |
+-------------------------+

2. Used in XML

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/button_background" />

inbutton_background.It is a nine-grid picture.

5. Production skills

1. Design principles

  • The four corner areas should contain content that does not want to be deformed (such as rounded corners and decorative elements)
  • Repeatable simple patterns should be used in the edge area
  • The center area can be solid color or simple texture

2. Common Errors

  • Forgot to add 1 pixel black edge
  • Black edge marks are not continuous
  • Too large marks in stretched areas lead to obvious deformation of the picture
  • Incorrect content area marking results in text misalignment

6. Advanced applications

1. Dynamically modify the nine-grid picture

// Get nine grid picturesNinePatchDrawable npd = (NinePatchDrawable) getResources()
    .getDrawable(.button_background);

// Modify the color filter(new PorterDuffColorFilter(
    , .SRC_IN));

// Apply to view(npd);

2. Code creation NinePatch

// Load the bitmapBitmap bitmap = (getResources(), 
    .button_background);

// Get NinePatch block databyte[] chunk = ();

// Create NinePatchDrawableNinePatchDrawable npd = new NinePatchDrawable(
    getResources(), 
    bitmap, 
    chunk, 
    new Rect(), 
    null);

7. Frequently Asked Questions

1. Black lines appear on the edge of the picture

  • Cause: The black edge mark is incorrectly included in the display area
  • Solution: Make sure to mark only at the outermost 1 pixel

2. The picture is stretched unevenly

  • Cause: Incorrect marking of stretched areas
  • Solution: Adjust the black edge mark to ensure that the stretchable area is reasonable

3. The content is incomplete

  • Cause: The content area (right/bottom) is marked incorrectly
  • Solution: Adjust the black mark on the right/bottom

4. Android Studio prompts “9-patch image malformed”

  • Reason: The nine-grid picture format is wrong
  • solve:
    1. Check if there is a 1-pixel black edge
    2. Check if the black edges are continuous
    3. Fix using Android Studio's drawing tools

8. Best Practices

  1. Naming Specifications:use_9Suffix, such asbtn_normal_9.png
  2. Minimum size: Make sure the picture is large enough to accommodate various stretching situations
  3. Test verification: Test the display effect on devices with different resolutions and sizes
  4. Alternative plan: Provide multiple versions of nine-grid pictures for different screen densities
  5. Alternatives: For simple shapes, consider using VectorDrawable or ShapeDrawable

9. Comparison with traditional PNG

characteristic Nine grid pictures Normal PNG
Stretching method Intelligent stretching Overall stretch
File size A little bigger Smaller
Neck protection Stay as it is Will deform
Applicable scenarios Buttons/Background Icons/Pictures
Production complexity Higher Low

Nine-grid pictures are powerful tools for handling stretchable backgrounds in Android development. Rational use can significantly improve the interface adaptability and visual effects of the application.

The above is the detailed explanation of the XML graphics files in the Android Drawable directory. For more information about Android Drawable XML graphics files, please follow my other related articles!