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

วิธีวาดรูปดาว (Star Shape) ด้วย Vector Drawable ใน Android

ภาพรวม

บทความนี้สาธิตการสร้างรูปดาว 5 จุด ด้วย 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/star_shape" />

</LinearLayout>

ขั้นตอนที่ 3: Vector Drawable (res/drawable/star_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="#FFD700"
        android:pathData="M12,2 L15.09,8.26 L22,9.27 L17,14.14 L18.18,21 L12,17.77 L5.82,21 L7,14.14 L2,9.27 L8.91,8.26 Z" />

</vector>

คำอธิบาย Path Data (ดาว 5 จุด)

พิกัดคำนวณจากวงกลมรัศมี 10 กึ่งกลาง (12,12):

  • จุดบน: (12, 2)
  • จุดขวาบน: (15.09, 8.26)
  • จุดขวา: (22, 9.27)
  • จุดขวาล่าง: (17, 14.14)
  • จุดล่างขวา: (18.18, 21)
  • จุดล่าง: (12, 17.77)
  • จุดล่างซ้าย: (5.82, 21)
  • จุดซ้ายล่าง: (7, 14.14)
  • จุดซ้าย: (2, 9.27)
  • จุดซ้ายบน: (8.91, 8.26)

สร้างดาวแบบโปรแกรม (Dynamic)

ถ้าต้องการดาวจุดต่างๆ (6 จุด, 8 จุด) ใช้ Kotlin extension:

fun createStarPath(points: Int, outerRadius: Float, innerRadius: Float): Path {
    val path = Path()
    val angleStep = Math.PI * 2 / (points * 2)
    var angle = -Math.PI / 2

    for (i in 0 until points * 2) {
        val radius = if (i % 2 == 0) outerRadius else innerRadius
        val x = 12 + radius * Math.cos(angle)
        val y = 12 + radius * Math.sin(angle)
        if (i == 0) path.moveTo(x.toFloat(), y.toFloat()) else path.lineTo(x.toFloat(), y.toFloat())
        angle += angleStep
    }
    path.close()
    return path
}

Vector Drawable แบบ Dynamic (API 24+)

<vector xmlns:android="https://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24">

    <path
        android:name="star"
        android:fillColor="#FFD700"
        android:pathData="M12,2 ..." />

    <!-- สามารถ animate ได้ด้วย AnimatedVectorDrawable -->
</vector>

การใช้งาน

  • Rating bar custom
  • Achievement badge
  • Favorite/Bookmark icon
  • Game UI elements

ทดสอบ

รันแอป จะเห็นดาวสีทองคำอยู่ตรงกลาง ขนาด 100x100dp