首先让我解释一下我的目标。我正在尝试制作一个Animation来更改ArcShape的属性。 ArcShape's构造函数具有两个字段:startAnglesweepAngle。我想设置sweepAngle的动画,使其在屏幕上显示为不断缩小的圆圈。

您可以通过想象PacMan来描绘此动画。想象一下他的嘴巴闭合。这种动画类似于他越来越张开上颚,直到不再有吃 bean 人为止。

现在...我在实现此问题上遇到了几个问题。首先,一旦创建了ArcShape,就没有内置的方法可以更改它的sweepAngle。这使我想到了第一个问题:是否有任何方法可以覆盖ArcShape并实现某些setSweepAngle方法?还是我必须为要显示的每个new ArcShape创建一个sweepAngle

现在继续第二个问题...假设我找到了第一个问题的解决方案,那么如何创建这个Animation呢?这是我现在拥有的要点:

public class OpenPacman extends Animation {
  public OpenPacman(float startAngle, float sweepAngle) {
    mStartAngle = startAngle;
    mSweepAngle = sweepAngle;
  }

  @Override
  protected void applyTransformation(float interpolatedTime, Transformation t) {
    /* This represents the current sweepAngle */
    float currAngle = mStartAngle + ((mSweepAngle - mStartAngle) * interpolatedTime);

    //Now I need to update the ArcShape's sweepAngle to currAngle. But HOW?
  }
}

最佳答案

我找到了解决方案。我有一个扩展View的类,我们将其称为Pacman,将我的自定义Animation嵌套在该Pacman类中。这使我可以访问member variables类的Pacman

public class Pacman extends View {
  float mSweepAngle;
  ...
  //include constructors
  //override onMeasure
  ...

  /* Here we override onDraw */
  @Override
  protected void onDraw(final Canvas canvas) {
    Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
    RectF oval = new RectF(canvas.getClipBounds());
    canvas.drawArc(oval, 0, mCurrAngle, true, p);
  }

  /* Here we define our nested custom animation */
  public class OpenPacman extends Animation {
    float mStartAngle;
    float mSweepAngle;

    public OpenPacman (int startAngle, int sweepAngle, long duration) {
      mStartAngle = startAngle;
      mSweepAngle = sweepAngle;
      setDuration(duration);
      setInterpolator(new LinearInterpolator());
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
      float currAngle = mStartAngle + ((mSweepAngle - mStartAngle) * interpolatedTime);
      Pacman.this.mCurrAngle = -currAngle; //negative for counterclockwise animation.
    }
  }
}

现在,当自定义动画更新容器类mCurrAngle时,会自动调用onDraw,它会绘制相应的ArcShape

10-08 03:46