Android 图像相对于中心点缩放动画?
androidapps/applicationsmobile development更新于 2026/2/3 0:37:17
此示例演示了 Android 图像相对于中心点缩放动画。
步骤 1 − 在 Android Studio 中创建一个新项目,转到"文件"->"新建项目",并填写所有必需的详细信息以创建新项目。
步骤 2 − 将以下代码添加到 res/layout/activity_main.xml。
<?xml version = "1.0" encoding = "utf-8"?> <RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://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 = "Click" 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>
在上面的代码中,我们已将按钮设置为显示图像缩放动画(Zoom animation)。
步骤 3 − 将以下代码添加到 src/MainActivity.java
package com.example.andy.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
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 fade_in = new ScaleAnimation(0f, 1f, 0f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
fade_in.setDuration(1000);
fade_in.setFillAfter(true);
view.startAnimation(fade_in);
}
});
}
}
当用户点击按钮时,它将使用以下代码显示图像缩放动画 -
ScaleAnimation fade_in = new ScaleAnimation(0f, 1f, 0f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); fade_in.setDuration(1000); fade_in.setFillAfter(true); view.startAnimation(fade_in);
让我们尝试运行您的应用程序。我假设您已将实际的 Android 移动设备连接到计算机。要从 Android Studio 运行应用,请打开项目的某个活动文件,然后点击工具栏上的"运行"图标
。选择您的移动设备作为选项,然后勾选将显示默认屏幕 −

在上面的屏幕中,我们使用了按钮,当用户点击按钮时,它会显示一个带有缩放效果的图像,如下所示 -

点击此处下载项目代码

