背景动画循环播放

7
在我的项目中,我想要像这样无限地使用一个大图案来动画化背景:

enter image description here

我最初想使用矩阵(用于缩放和平移)和ValueAnimator创建平移动画,但我不知道如何重复图案。有什么方法可以实现这种效果吗?谢谢你的帮助。
更新:我的源代码没有重复(注意:在GIF动画中,我水平绘制了图案以简化表示,但实际上我需要垂直平移动画)。
background.setImageResource(R.drawable.background);
background.setScaleType(ScaleType.MATRIX);

ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    private Matrix matrix = new Matrix();
    @Override public void onAnimationUpdate(ValueAnimator animation) {
        float factor = (Float) animation.getAnimatedValue();
        int width = background.getDrawable().getIntrinsicWidth();
        int height = background.getDrawable().getIntrinsicHeight();
        float scale = (float) background.getWidth() / (float) width;
        matrix.reset();
        matrix.postTranslate(0, -height * factor);
        matrix.postScale(scale, scale);
        background.setImageMatrix(matrix);
    }
});

animator.setInterpolator(new LinearInterpolator());
animator.setRepeatCount(ValueAnimator.INFINITE);
animator.setRepeatMode(ValueAnimator.RESTART);
animator.setDuration(10000);
animator.start();
1个回答

2
我终于扩展了BitmapDrawable以覆盖draw()方法:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.background);
BitmapDrawable drawable = new BitmapDrawable(getResources(), bitmap) {
    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        canvas.drawBitmap(getBitmap(), 0, getIntrinsicHeight(), null);
    }
};

background.setImageDrawable(drawable);
background.setScaleType(ScaleType.MATRIX);

ValueAnimator animator = ValueAnimator.ofFloat(0);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    private Matrix matrix = new Matrix();
    @Override
    public void onAnimationUpdate(ValueAnimator animator) {
        matrix.reset();
        int height = background.getDrawable().getIntrinsicHeight();
        float translate = -height * animator.getAnimatedFraction();
        matrix.postTranslate(0, translate);
        float width = background.getDrawable().getIntrinsicWidth();
        float scale = background.getWidth() / width;
        matrix.postScale(scale, scale);
        background.setImageMatrix(matrix);
    }
});

animator.setInterpolator(new LinearInterpolator());
animator.setRepeatCount(ValueAnimator.INFINITE);
animator.setRepeatMode(ValueAnimator.RESTART);
animator.setDuration(10000);
animator.start();

注意:drawable.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT)imageView.setScaleType(ScaleType.MATRIX)不兼容。
因此,我不知道这是否是一种好的做法,但目前这是我找到的唯一方法。如果您有任何改进技术的想法,请分享。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接