Giới thiệu
Ví dụ này minh họa cách hiển thị văn bản lên trên hình ảnh (overlay text on image) trong Android bằng cách sử dụng RelativeLayout xếp chồng lớp.
Các bước thực hiện
Bước 1: Tạo dự án mới
Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.
Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:padding="8dp"
tools:context=".MainActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@drawable/image"/>
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="16sp"
android:padding="4dp"
android:textSize="24sp"
android:textStyle="bold|italic"
android:textColor="#FFFFFF"
android:shadowColor="#000000"
android:shadowDx="2"
android:shadowDy="2"
android:shadowRadius="4"/>
</RelativeLayout>
Bước 3: Viết code MainActivity.java
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
textView.setText("Đây là nơi tôi muốn sống");
textView.setTextColor(Color.WHITE);
}
}
Cách nâng cao (vẽ trực tiếp lên Bitmap):
public Bitmap drawTextOnBitmap(Bitmap bitmap, String text) {
Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.WHITE);
paint.setTextSize(60);
paint.setStyle(Paint.Style.FILL);
paint.setShadowLayer(4, 2, 2, Color.BLACK);
// Tính vị trí canh giữa
float x = (canvas.getWidth() - paint.measureText(text)) / 2;
float y = canvas.getHeight() - 50;
canvas.drawText(text, x, y, paint);
return mutableBitmap;
}
Bước 4: Cấu hình AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Chạy ứng dụng
Đặt một hình ảnh tên image.png trong thư mục res/drawable. Kết nối thiết bị, nhấn Run.
