Giới thiệu
Ví dụ này minh họa cách tạo animation phóng to (zoom/scale) ImageView từ tâm hình ảnh bằng ScaleAnimation.
Bước 1: Tạo dự án mới
Android Studio → File → New Project.
Bước 2: 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">
<Button
android:id="@+id/button"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:layout_width="150dp"
android:text="Zoom"
android:layout_height="wrap_content"/>
<ImageView
android:id="@+id/imageView"
android:src="@mipmap/ic_launcher_round"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Bước 3: Logic zoom (src/MainActivity.java)
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
ImageView view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = findViewById(R.id.imageView);
view.setVisibility(View.INVISIBLE);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ScaleAnimation fadeIn = new ScaleAnimation(
0f, 1f, // fromX, toX (0% → 100% width)
0f, 1f, // fromY, toY (0% → 100% height)
Animation.RELATIVE_TO_SELF, 0.5f, // pivotX: 50% width (tâm ngang)
Animation.RELATIVE_TO_SELF, 0.5f // pivotY: 50% height (tâm dọc)
);
fadeIn.setDuration(1000);
fadeIn.setFillAfter(true);
view.startAnimation(fadeIn);
}
});
}
}
Giải thích ScaleAnimation constructor
new ScaleAnimation(
float fromX, float toX,
float fromY, float toY,
int pivotXType, float pivotXValue,
int pivotYType, float pivotYValue
)
0f → 1f: Scale từ 0% đến 100% (phóng to từ không thấy lên full size)RELATIVE_TO_SELF, 0.5f: Điểm neo (pivot) ở 50% kích thước View = tâm- Các loại pivotType:
RELATIVE_TO_SELF,RELATIVE_TO_PARENT,ABSOLUTE
Chạy ứng dụng
Chạy app → Ban đầu ImageView ẩn. Nhấn "Zoom" → ImageView phóng to từ tâm ra ngoài trong 1 giây.
Biến thể: Zoom out (thu nhỏ)
ScaleAnimation fadeOut = new ScaleAnimation(
1f, 0f, 1f, 0f,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f
);