Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีวาดไอคอนโปรไฟล์ (Profile/User Icon) ด้วย Vector Drawable

ภาพรวม

บทความนี้สาธิตการสร้างไอคอนผู้ใช้ (User/Profile Icon) แบบเวกเตอร์ ประกอบด้วยหัวและไหล่

ขั้นตอนที่ 1: สร้างโปรเจกต์

Android Studio → File → New Project → Empty Activity

ขั้นตอนที่ 2: Layout (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:layout_marginTop="30dp"
    tools:context=".MainActivity">

    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="@drawable/profile_icon" />

</LinearLayout>

ขั้นตอนที่ 3: Vector Drawable (res/drawable/profile_icon.xml)

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="https://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24">

    <!-- หัว (วงกลม) -->
    <path
        android:fillColor="#D80027"
        android:pathData="M12,4C9.79,4 8,5.79 8,8s1.79,4 4,4 4,-1.79 4,-4-1.79,-4 -4,-4zm0,6c-1.1,0 -2,-0.9 -2,-2s0.9,-2 2,-2 2,0.9 2,2-0.9,2 -2,2z" />

    <!-- ไหล่/ร่างกาย (โค้ง) -->
    <path
        android:fillColor="#D80027"
        android:pathData="M12,14c-4.42,0 -8,3.58 -8,8v2h16v-2c0,-4.42 -3.58,-8 -8,-8z" />

</vector>

คำอธิบาย Path

หัว (Circle)

M12,4 C9.79,4 8,5.79 8,8 S9.79,12 12,12 S16,10.21 16,8 S14.21,4 12,4 Z
  • วงกลมกึ่งกลาง (12,8) รัศมี 4

ไหล่ (Shoulders)

M12,14 C7.58,14 4,17.58 4,22 V24 H20 V22 C20,17.58 16.42,14 12,14 Z
  • โค้งควอдраติกจาก (4,22) ถึง (20,22) ควบคุมที่ (12,14)

รูปแบบอื่นๆ

ไอคอนผู้ใช้แบบเรียบ (Material Design)

<vector android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
    <path android:fillColor="#000000"
        android:pathData="M12,12c2.21,0 4,-1.79 4,-4s-1.79,-4 -4,-4 -4,1.79 -4,4 1.79,4 4,4zm0,2c-2.67,0 -8,1.34 -8,4v2h16v-2c0,-2.66 -5.33,-4 -8,-4z"/>
</vector>

ไอคอนกลุ่มผู้ใช้ (Group)

<vector ...>
    <path android:fillColor="#000"
        android:pathData="M16,11c1.66,0 2.99,-1.34 2.99,-3S17.66,5 16,5c-1.66,0 -3,1.34 -3,3s1.34,3 3,3zm-8,0c1.66,0 2.99,-1.34 2.99,-3S9.66,5 8,5C6.34,5 5,6.34 5,8s1.34,3 3,3zm0,2c-2.33,0 -7,1.17 -7,3.5V19h14v-2.5c0,-2.33 -4.67,-3.5 -7,-3.5zm8,0c-.29,0 -.62,.02 -.97,.05 1.16,.84 1.97,1.97 1.97,3.45V19h6v-2.5c0,-2.33 -4.67,-3.5 -7,-3.5z"/>
</vector>

การใช้งาน

  • Profile avatar placeholder
  • Navigation drawer header
  • User list item
  • Account settings

ทดสอบ

รันแอป จะเห็นไอคอนโปรไฟล์สีแดง (#D80027) อยู่ตรงกลาง