我最近在做的APP中也有同样的需求。
阅读KenBurnsView的源代码后,这是一个可行的TransitionGenerator
:
public static class ScanTransitionGenerator implements TransitionGenerator {
private static final int DEFAULT_TRANSITION_DURATION = 5000;
private static final Interpolator DEFAULT_TRANSITION_INTERPOLATOR = new AccelerateDecelerateInterpolator();
private long transitionDuration;
private Interpolator transitionInterpolator;
private Transition lastTransition;
private RectF lastDrawableBounds;
private boolean forward;
public ScanTransitionGenerator() {
transitionDuration = DEFAULT_TRANSITION_DURATION;
transitionInterpolator = DEFAULT_TRANSITION_INTERPOLATOR;
}
@Override
public Transition generateNextTransition(RectF drawableBounds, RectF viewport) {
float drawableRatio = getRectRatio(drawableBounds);
float viewportRectRatio = getRectRatio(viewport);
RectF startRect;
RectF endRect;
if (drawableRatio >= viewportRectRatio) {
float w = drawableBounds.height() * viewportRectRatio;
float h = drawableBounds.height();
startRect = new RectF(0, 0, w, h);
endRect = new RectF(drawableBounds.width() - w, 0, drawableBounds.width(), h);
} else {
float w = drawableBounds.width();
float h = drawableBounds.width() / viewportRectRatio;
startRect = new RectF(0, 0, w, h);
endRect = new RectF(0, drawableBounds.height() - h, w, drawableBounds.height());
}
if (!drawableBounds.equals(lastDrawableBounds) || !haveSameAspectRatio(lastTransition.getDestinyRect(), viewport)) {
forward = false;
}
forward = !forward;
if (forward) {
lastTransition = new Transition(startRect, endRect, transitionDuration, transitionInterpolator);
} else {
lastTransition = new Transition(endRect, startRect, transitionDuration, transitionInterpolator);
}
lastDrawableBounds = new RectF(drawableBounds);
return lastTransition;
}
private static boolean haveSameAspectRatio(RectF r1, RectF r2) {
return (Math.abs(getRectRatio(r1) - getRectRatio(r2)) <= 0.01f);
}
private static float getRectRatio(RectF rect) {
return rect.width() / rect.height();
}
}