ภาพรวม
บทความนี้สาธิตการสร้างรูปหัวใจด้วย Vector Drawable XML
ขั้นตอนที่ 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/heart_shape" />
</LinearLayout>
ขั้นตอนที่ 3: Vector Drawable (res/drawable/heart_shape.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="#E91E63"
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" />
</vector>
คำอธิบาย Path Data
ใช้ Bezier Curves สร้างโค้งหัวใจ:
- เริ่มกึ่งกลางล่าง (12, 21.35)
- โค้งไปซ้ายบน ควบคุมด้วยจุดควบคุม
- โค้งกลับมาขวาบน
- ปิดที่จุดเริ่มต้น
รูปหัวใจแบบต่างๆ
หัวใจทึบ (Filled) - แดง
<path android:fillColor="#FF0000" 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,.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" />
หัวใจขอบ (Outline) - สำหรับปุ่ม Like
<vector ...>
<path
android:fillColor="#00000000"
android:strokeColor="#FF0000"
android:strokeWidth="2"
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,.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" />
</vector>
State List สำหรับปุ่ม Like (Filled ↔ Outline)
res/drawable/heart_button.xml:
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@drawable/heart_filled" />
<item android:drawable="@drawable/heart_outline" />
</selector>
ใช้กับ CheckBox หรือ ToggleButton:
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/heart_button"
android:background="?attr/selectableItemBackgroundBorderless" />
Animation: Heart Beat
res/anim/heart_beat.xml:
<set xmlns:android="https://schemas.android.com/apk/res/android">
<scale
android:duration="300"
android:fromXScale="1.0" android:toXScale="1.3"
android:fromYScale="1.0" android:toYScale="1.3"
android:pivotX="50%" android:pivotY="50%"
android:repeatCount="1" android:repeatMode="reverse" />
</set>
ทดสอบ
รันแอป จะเห็นหัวใจสีชมพูแดง (#E91E63) อยู่ตรงกลาง ขนาด 100x100dp