Android 使用动画使物体利用重力落向地面

Android using animation to make an object fall towards the ground using gravity

我是 Android 开发的新手,我正在尝试在屏幕顶部创建一个图像并使其落到底部。我一直在环顾四周,无法在正确的方向上得到直接的答案或指示。我发现的许多示例都已过时,并且许多方法不再有效。

我的可绘制文件夹中有一张图片,我想在 10 秒后创建它,让它像有重力一样落向地面。

关于ObjectAnimator、canvas、速度、动画我见多了。我不知道从哪里开始。

如果要模拟真实重力,难度很大,需要安装其他外部库。您还需要做很多数学运算才能使重力起作用。

真正的重力:物体会加速和弹跳等等

但是如果你只是想让东西以恒定的速度从上到下掉落(没有加速度),那就更容易了。

您只需在项目的 anim 文件夹中创建一个新的 xml 文件,然后将其加载到您的代码中。有很多教程可以做到这一点:http://developer.android.com/guide/topics/graphics/view-animation.html

真的很简单! (XML事情总是很容易,不是吗?)

一定要查看 ViewPropertyAnimator class 及其方法。 对于加速和弹跳等,有所谓的插值器,使动画更逼真/逼真。我能想到的最简单的方法是这样的:

假设您在 xml 文件中有一个 RelativeLayout 作为父级和一个 ImageView 作为子级:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/your_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:src="@mipmap/ic_launcher" />
</RelativeLayout>

然后在您的 Java 代码中像这样启动动画:

ImageView imageView = (ImageView) findViewById(R.id.your_image);

float bottomOfScreen = getResources().getDisplayMetrics()
    .heightPixels - (imageView.getHeight() * 4);
        //bottomOfScreen is where you want to animate to

imageView.animate()
    .translationY(bottomOfScreen)
    .setInterpolator(new AccelerateInterpolator())
    .setInterpolator(new BounceInterpolator())
    .setDuration(2000);

这应该让你开始了。

摘录:

Handler h=new Handler();
ImageView img;

Runnable r= new Runnable()
        {
        @Override public void run() {img.invalidate();}
        };

@Override 
protected void onCreate(Bundle b)
{
    super.onCreate(b);
    p.setColor(Color.RED);
    p.setStyle(Paint.Style.FILL_AND_STROKE);
    p.setDither(false);
    p.setStrokeWidth(3);
    p.setAntiAlias(true);       
    p.setColor(Color.parseColor("#CD5C5C"));
    p.setStrokeWidth(15);
    p.setStrokeJoin(Paint.Join.ROUND);    
    p.setStrokeCap(Paint.Cap.ROUND);

    img=new ImageView(this)
        {   
            @Override protected void onDraw(Canvas cnv)
            {
                x+=i;
                y+=j;
                if(x>300)i=-1;
                if(y>300)j=-1;
                if(x<0)i=1;
                if(y<0)j=1;

                cnv.drawPoint(x,y,p);
                h.postDelayed(r,fps);   

重点是我们需要从处理 运行 固定 fps 线程的外部句柄调用对用户界面主线程的更新。

在此处查看完整代码: Thread Runnable Handle to Graphic Animation Bouncing Ball like Pixels