Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách thêm hiệu ứng bóng (shadow) cho TextView trong Android

Giới thiệu

Ví dụ này minh họa cách thêm hiệu ứng bóng (shadow) cho văn bản trong TextView chỉ bằng XML, không cần code Java.

Bước 1: Tạo dự án mới

Android Studio → File → New Project.

Bước 2: Giao diện với shadow XML (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/parent"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:id="@+id/text"
        android:textSize="28sp"
        android:textAlignment="center"
        android:textColor="#FFFFFF"
        android:layout_width="match_parent"
        android:shadowColor="#000000"
        android:shadowDx="-2"
        android:shadowDy="-2"
        android:shadowRadius="1"
        android:layout_height="wrap_content" />

</LinearLayout>

Giải thích các thuộc tính shadow

Thuộc tínhGiá trịÝ nghĩa
android:shadowColor#000000Màu bóng (đen)
android:shadowDx-2Độ lệch ngang (âm = trái, dương = phải)
android:shadowDy-2Độ lệch dọc (âm = trên, dương = dưới)
android:shadowRadius1Bán kính làm mờ bóng (càng lớn càng mờ)

Bước 3: Activity (src/MainActivity.java)

package com.example.andy.myapplication;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    int view = R.layout.activity_main;
    TextView textview;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(view);
        textview = findViewById(R.id.text);
        textview.setText("TextView có hiệu ứng bóng");
    }
}

Chạy ứng dụng

Chạy app → TextView hiển thị chữ trắng có bóng đen lệch lên-trái 2px, bán kính mờ 1px.

Mẹo thiết kế

  • Để chữ dễ đọc trên nền phức tạp: dùng shadowColor tối, shadowRadius 2-4
  • Hiệu ứng "letterpress": shadowColor="#FFFFFF", shadowDx=1, shadowDy=1, shadowRadius=1 trên chữ tối
  • Neon glow: shadowColor cùng tone chữ, shadowRadius lớn (5-10), shadowDx=0, shadowDy=0