Skip to content

Instantly share code, notes, and snippets.

@odbol
Last active Dec 4, 2020
Embed
What would you like to do?
Various utilities for animation and graphics.
package com.odbol.utils;
/**
* Various utilities for animation and graphics.
*/
public class AnimationUtils {
/**
* Interpolate a value with specified extrema, to a new value between new extrema.
*
* @param value the current value
* @param inputMin minimum the input value can reach
* @param inputMax maximum the input value can reach
* @param outputMin minimum the output value can reach
* @param outputMax maximum the output value can reach
*/
public static float map(float value, float inputMin, float inputMax, float outputMin, float outputMax) {
return outputMin + (outputMax - outputMin) * ((value - inputMin) / (inputMax - inputMin));
}
/**
* Same as {@link #map}, but clamps the values so they never exceed the extrema.
*/
public static float mapClamped(float value, float inputMin, float inputMax, float outputMin, float outputMax) {
return Math.max(outputMin, Math.min(outputMax, map(value, inputMin, inputMax, outputMin, outputMax)));
}
/***
* Interpolate between values a and b.
*/
public static float lerp(float a, float b, float fraction)
{
return (float) ((a * (1.0 - fraction)) + (b * fraction));
}
}
package com.odbol.utils;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import androidx.dynamicanimation.animation.DynamicAnimation;
import androidx.dynamicanimation.animation.DynamicAnimation.OnAnimationEndListener;
import io.reactivex.rxjava3.core.Single;
public class RxUtils {
/**
* Starts an animation and completes once the animation finishes.
*
* The observed value is true if the animation ended, false if it was canceled.
*/
public static Single<Boolean> startAnimationAndWaitForEnd(Animator animator) {
return Single.create(emitter -> {
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationCancel(Animator animation) {
animator.removeListener(this);
emitter.onSuccess(false);
}
@Override
public void onAnimationEnd(Animator animation) {
animator.removeListener(this);
emitter.onSuccess(true);
}
});
animator.start();
});
}
/**
* Starts an animation and completes once the animation finishes.
*
* The observed value is true if the animation ended, false if it was canceled.
*/
public static <T extends DynamicAnimation<T>> Single<Boolean> startAnimationAndWaitForEnd(DynamicAnimation<T> animator) {
return Single.create(emitter -> {
animator.addEndListener(new OnAnimationEndListener() {
@Override
public void onAnimationEnd(DynamicAnimation animation, boolean canceled, float value, float velocity) {
animator.removeEndListener(this);
emitter.onSuccess(!canceled);
}
});
animator.start();
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment