# 更加自然的渐变——呼吸动画

·  阅读 8971

k=1/3，t=6, n={1,2,3,...}

(函数，及以上图片出自上文提到的链接)

``````x=0:0.0000001:6;
k=1/3;
t=6;
n=1;
y=(0.5*sin((pi/(k*t)).*((x-k*t/2)-(n-1)*t))+0.5).*(x>=(n-1)*t&x<(n-(1-k))*t)+((0.5*sin((pi/((1-k)*t)).*((x-(3-k)*t/2)-(n-1)*t))+0.5).^2).*(x>=(n-(1-k))*t&x<n*t);
grid on;
axis equal
axis([0 8 0 3])复制代码``````

``````package com.jaren.breatheanimationdemo;

import android.animation.TimeInterpolator;

/**
* 定义拟合呼吸变化的插值器
*/

public class BraetheInterpolator implements TimeInterpolator {
@Override
public float getInterpolation(float input) {

float x = 6 * input;
float k = 1.0f / 3;
int t = 6;
int n = 1;//控制函数周期，这里取此函数的第一个周期
float PI = 3.1416f;
float output = 0;

if (x >= ((n - 1) * t) && x < ((n - (1 - k)) * t)) {
output = (float) (0.5 * Math.sin((PI / (k * t)) * ((x - k * t / 2) - (n - 1) * t)) + 0.5);

} else if (x >= (n - (1 - k)) * t && x < n * t) {
output = (float) Math.pow((0.5 * Math.sin((PI / ((1 - k) * t)) * ((x - (3 - k) * t / 2) - (n - 1) * t)) + 0.5), 2);
}
return output;
}
}

``````  /**
* 开启透明度渐变呼吸动画
*/
private void startAlphaBreathAnimation() {
ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(tvShowBreathing, "alpha", 0f, 1f);
alphaAnimator.setDuration(4000);
alphaAnimator.setInterpolator(new BraetheInterpolator());//使用自定义的插值器
alphaAnimator.setRepeatCount(ValueAnimator.INFINITE);
alphaAnimator.start();
}复制代码``````

`````` /**
* 开启缩放渐变呼吸动画
*/
private void startScaleBreathAnimation() {
ObjectAnimator scaleX = ObjectAnimator.ofFloat(tvShowBreathing, "scaleX", 0.4f, 1f);
ObjectAnimator scaleY = ObjectAnimator.ofFloat(tvShowBreathing, "scaleY", 0.4f, 1f);
scaleX.setRepeatCount(ValueAnimator.INFINITE);
scaleY.setRepeatCount(ValueAnimator.INFINITE);
AnimatorSet animatorSet=new AnimatorSet();
animatorSet.playTogether(scaleX,scaleY);
animatorSet.setDuration(4000 );
animatorSet.setInterpolator(new BraetheInterpolator());
animatorSet.start();

}复制代码``````

``````   animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
animation.getAnimatedValue();
//...
}
});复制代码``````

Android

Android