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

วิธีวาดรูปสามเหลี่ยม (Triangle) ด้วย Vector Drawable ใน Android

ภาพรวม

บทความนี้สาธิตการสร้างรูปสามเหลี่ยมด้วย Vector Drawable (.xml) ซึ่งขยายขนาดได้ไม่เสียคุณภาพ (Resolution Independent)

ขั้นตอนที่ 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/triangle_background" />

</LinearLayout>

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

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

    <path
        android:fillColor="#000000"
        android:pathData="M12,2 L22,22 L2,22 Z" />

</vector>

คำอธิบาย Path Data

  • M12,2 - Move to จุดกึ่งกลางบน (12,2)
  • L22,22 - Line to มุมขวาล่าง
  • L2,22 - Line to มุมซ้ายล่าง
  • Z - Close path (กลับสู่จุดเริ่มต้น)

รูปสามเหลี่ยมรูปแบบต่างๆ

สามเหลี่ยมหน้าจั่ว (ชี้ขึ้น)

<path android:fillColor="#FF5722"
    android:pathData="M12,2 L22,22 L2,22 Z" />

สามเหลี่ยมหน้าจั่ว (ชี้ลง)

<path android:fillColor="#4CAF50"
    android:pathData="M2,2 L22,2 L12,22 Z" />

สามเหลี่ยมฉาก (ชี้ขวา)

<path android:fillColor="#2196F3"
    android:pathData="M2,2 L22,12 L2,22 Z" />

สามเหลี่ยมสมมาตร (Equilateral) - คำนวณพิกัด

<vector
    android:width="100dp"
    android:height="100dp"
    android:viewportWidth="200"
    android:viewportHeight="173.2">  <!-- sqrt(3)/2 * 200 -->
    <path
        android:fillColor="#9C27B0"
        android:pathData="M100,0 L200,173.2 L0,173.2 Z" />
</vector>

การใช้งาน

  • ตั้งเป็น background ของ View ใดๆ
  • ใช้ใน ImageView
  • ใช้เป็น drawableStart/End ใน TextView, Button, EditText
  • นำไปทำ Animation ได้ (rotate, scale, morph)

ข้อดีของ Vector Drawable

  • ขนาดไฟล์เล็กมาก
  • ขยาย/ย่อได้ไม่เสียคุณภาพ
  • แก้ไขสี/ขนาดได้ง่ายใน XML
  • รองรับ Animation (AnimatedVectorDrawable)

ทดสอบ

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