จบทุกปัญหา ImageView ด้วย Dimension Ratio
Published in
1 min readMar 12, 2020
Dimension Ratio เป็นความสามารถอย่างหนึ่งของ Constraint Layout ใช้สำหรับ รักษาสัดส่วน (Ratio) ให้กับ widget เช่น ImageView Button CustomView etc.
Attribute ที่ใช้งาน
app:layout_constraintDimensionRatio="width:height"
รูปแบบการใช้งาน
app:layout_constraintDimensionRatio="16:9"app:layout_constraintDimensionRatio="H,16:9"app:layout_constraintDimensionRatio="W,9:16"app:layout_constraintDimensionRatio="16.55555:9.555555"
ตัวอย่างการใช้งานกับ ImageView
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"> <ImageView
android:layout_width="0dp"
android:layout_height="0dp"
android:src="@drawable/image_16_9"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintDimensionRatio="16:9"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" /></androidx.constraintlayout.widget.ConstraintLayout>
กำหนด android:layout_width=”0dp” และ android:layout_height=”0dp” เพื่อให้ ImageView แสดง ratio ได้ถูกต้อง
ผลลัพธ์
หวังว่าบทความนี้จะเป็นประโยชน์กับทุกคน ครั้งหน้าหากเจอ ImageView หรือ Widget อื่นๆ ลองนำ dimension ratio ไปใช้งานกันดูนะคะ