CircularImageView là thành phần UI phổ biến để hiển thị ảnh tròn (avatar, profile). Android không có sẵn view này, nhưng có thể dễ dàng tích hợp qua thư viện. Bài viết hướng dẫn sử dụng thư viện CircularImageView của Mikhael Lopez.
Các bước tích hợp
Bước 1: Tạo project mới
File → New Project trong Android Studio, điền thông tin cần thiết.
Bước 2: Thêm dependency vào build.gradle (Module: app)
dependencies {
implementation 'com.mikhaellopez:circularimageview:3.2.0'
// Các dependency khác...
}
Bước 3: MainActivity.java - Không cần code thêm
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Bước 4: Layout activity_main.xml với CircularImageView
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical">
<com.mikhaellopez.circularimageview.CircularImageView
android:layout_width="250dp"
android:layout_height="250dp"
android:src="@drawable/your_image"
app:civ_border_color="#EEEEEE"
app:civ_border_width="4dp"
app:civ_shadow="true"
app:civ_shadow_radius="10"
app:civ_shadow_color="#8BC34A"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Tên người dùng"
android:textSize="20sp"
android:textAlignment="center"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Các thuộc tính chính của CircularImageView
| Thuộc tính | Mô tả | Giá trị mặc định |
|---|---|---|
| app:civ_border | Bật/tắt viền | true |
| app:civ_border_color | Màu viền | Trắng |
| app:civ_border_width | Độ rộng viền | 4dp |
| app:civ_background_color | Màu nền | Trắng |
| app:civ_shadow | Bật/tắt đổ bóng | false |
| app:civ_shadow_color | Màu đổ bóng | Đen |
| app:civ_shadow_radius | Bán kính đổ bóng | 8.0f |
| app:civ_shadow_gravity | Hướng đổ bóng | bottom |
Chạy ứng dụng
Đảm bảo có ảnh trong thư mục drawable (thay @drawable/your_image bằng ảnh thực). Build và chạy app để xem kết quả ảnh tròn với viền và đổ bóng.
Lưu ý
- Thư viện này hỗ trợ cả ảnh tĩnh và GIF animation
- Có thể thiết lập các thuộc tính bằng code Java/Kotlin thay vì XML
- Hiệu suất tốt, nhẹ (~20KB)