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

Cách scale ảnh trong ImageView giữ nguyên tỷ lệ khung hình trên Android

Ví dụ này minh họa cách scale ảnh trong ImageView để giữ nguyên tỷ lệ khung hình (aspect ratio) trên Android.

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

Tạo dự án mới trong Android Studio: File → New Project, điền đầy đủ thông tin cần thiết.

Bước 2: Cấu hình layout (res/layout/activity_main.xml)

<?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">
    <ImageView
        android:id="@+id/my_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true"
        android:adjustViewBounds="true"
        android:scaleType="fitCenter"
        tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>

Lưu ý quan trọng: Sử dụng android:scaleType="fitCenter" kết hợp với android:adjustViewBounds="true" để ảnh scale giữ nguyên tỷ lệ. Thuộc tính fitXY trong ví dụ gốc sẽ làm méo ảnh.

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

package com.app.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView myImage = findViewById(R.id.my_image);
        myImage.setImageResource(R.drawable.flower);
    }
}

Bước 4: Cấu hình Manifest (AndroidManifest.xml)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.app.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

Kết nối thiết bị Android thật, chọn Run từ toolbar, chọn thiết bị để xem kết quả. Ảnh sẽ hiển thị toàn màn hình nhưng vẫn giữ tỷ lệ gốc.

Cách scale ảnh trong ImageView giữ nguyên tỷ lệ khung hình trên Android