您将如何为类似于View的Drawable实现setScaleX和setTranslateX?

问题描述 投票:0回答:1

我想在自定义Drawable上使用ObjectAnimator(它包装另一个内部drawable toEducate只是为了赋予它们这些动画功能)。

我已经尝试了以下方法,但是动画没有达到预期的效果。

我的实现缺少任何内容?

  public void setScaleX(float scaleX) {
    Rect bounds = toEducate.copyBounds();
    bounds.right = (int) (bounds.right + scaleX/2);
    bounds.left = (int) (bounds.left - scaleX/2);
    toEducate.setBounds(bounds);
    toEducate.invalidateSelf();
    this.invalidateSelf();
  }

 public void setTranslationX(float translationX) {
    Rect bounds = toEducate.copyBounds();
    bounds.right = (int) (bounds.right + translationX);
    bounds.left = (int) (bounds.left + translationX);
    toEducate.setBounds(bounds);
    toEducate.invalidateSelf();
    this.invalidateSelf();
  }

播放此动画:

    educationAnimatorSet.playTogether(
        ImmutableList.of(
            ObjectAnimator.ofFloat(educationDrawable, "translationX", 1000).setDuration(2000),
            ObjectAnimator.ofFloat(educationDrawable, "translationY", 1000).setDuration(2000)));

    educationAnimatorSet.playTogether(
        ImmutableList.of(
            ObjectAnimator.ofFloat(educationDrawable, "scaleX", 1000).setDuration(2000),
            ObjectAnimator.ofFloat(educationDrawable, "scaleY", 1000).setDuration(2000)));
android animation drawable android-drawable objectanimator
1个回答
0
投票

setScaleX方法中的数学看起来错误,因为它没有增加宽度scaleX倍,我的意思是这行:

public void setScaleX(float scaleX) {
    ...
    bounds.right = (int) (bounds.right + scaleX/2);
    bounds.left = (int) (bounds.left - scaleX/2); 
    ...
} 

我认为方法应该是这样的(对于中心的枢轴点)

    public void setScaleX(float scaleX) {
        int centerX = bounds.left + bounds.width/2;
        int newWidth = bounds.width * scaleX;

        Rect bounds = toEducate.copyBounds();
        bounds.right = centerX + newWidth/2
        bounds.left = centerX - newWidth/2
        toEducate.setBounds(bounds);
        toEducate.invalidateSelf();
        this.invalidateSelf();
    }

还检查getScaleXgetScaleYgetTranslationXgetTranslationY方法是否存在并返回正确的值。据我所知,还应该提供自定义动画属性的吸气剂。

© www.soinside.com 2019 - 2024. All rights reserved.