仿快递柜开门动画
实现效果
原理:
通过错切和宽度动画实现开关门效果
实现代码:
ButtonWrapper,实现按钮宽度动画
public class ButtonWrapper {
private Button button;
public ButtonWrapper(Button button) {
this.button = button;
}
public int getWidth() {
return button.getLayoutParams().width;
}
public void setWidth(int width) {
button.getLayoutParams().width = width;
button.requestLayout();
}
public int getHeight() {
return button.getLayoutParams().height;
}
public void setHeight(int height) {
button.getLayoutParams().height = height;
button.requestLayout();
}
}
SkewAnimation,实现错切效果
public class SkewAnimation extends Animation {
private long duration;
private boolean fillAfter;
private boolean open;
public Rotate3dAnimation(long duration, boolean fillAfter) {
this.duration = duration;
this.fillAfter = fillAfter;
}
public void setOpen(boolean open) {
this.open = open;
}
@Override
public void initialize(int width, int height, int parentWidth, int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
setDuration(duration);
setFillAfter(fillAfter);
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
final Matrix matrix = t.getMatrix();
matrix.reset();
if (open) {
matrix.setSkew(0, 0.2f * interpolatedTime);
} else {
matrix.setSkew(0, 0.2f * (1f - interpolatedTime));
}
}
}
代码使用
public void openDoor(View view) {
Rotate3dAnimation rotation = new Rotate3dAnimation(500, true);
rotation.setOpen(true);
button.startAnimation(rotation);
ButtonWrapper wrapper = new ButtonWrapper(button);
addViewSkewAnim = ObjectAnimator.ofInt(wrapper, "width", 143, 60);
addViewSkewAnim.setDuration(500);
addViewSkewAnim.start();
}
public void closeDoor(View view) {
Rotate3dAnimation rotation = new Rotate3dAnimation(500, true);
rotation.setOpen(false);
button.startAnimation(rotation);
ButtonWrapper wrapper = new ButtonWrapper(button);
addViewSkewRevertAnim = ObjectAnimator.ofInt(wrapper, "width", 60, 143);
addViewSkewRevertAnim.setDuration(500);
addViewSkewRevertAnim.start();
}