闲来无事造个轮子,之前无意间看到一个酷炫的登陆按钮,点击之后会缩成一团旋转,loading完成后再展开,于是自己试着模仿了一下,效果图如下
一.思路
动画可以拆分为三部分:
1.将矩形按钮缩成圆型,首先隐藏title,然后改变按钮的frame为位于中心点的以原有高度为边长正方形,最后裁切圆角,达到效果。
2.旋转圆形按钮,首先需要添加一个白色小弧线,可以采用CAShapeLayer实现,然后让按钮绕Z轴旋转,可以采用CABasicAnimation实现。
3.将圆形按钮展开成矩形,首先还原按钮的frame,然后还原圆角,最后显示title。
二.核心代码
1.对外接口
#import <UIKit/UIKit.h>
typedef void (^CallBack)();
@interface VDLoadingButton : UIButton
/**
初始化VDLoadingButton
@param frame 按钮的frame
@param backgroundColor 按钮的背景颜色
@param title 按钮的文字
@param titleColor 文字颜色
@param titleFont 文字字体大小
@param cornerRadius 按钮圆角半径
@param clickBlock 按钮点击之后执行的代码块
@return 初始化完成的VDLoadingButton
*/
+ (instancetype)VDLoadingButtoninitWithFrame:(CGRect)frame andBackgroundColor:(UIColor *)backgroundColor andTitle:(NSString *)title andTitleColor:(UIColor *)titleColor andTitleFont:(UIFont *)titleFont andCornerRadius:(CGFloat)cornerRadius andClickBlock:(CallBack)clickBlock;
/**
停止VDLoadingButton的动画
@param callBack 动画停止之后执行的代码块
*/
- (void)stopAnimateAndCallBack:(CallBack)callBack;
@end
2.动画实现
- (void)loginButtonDidClick {
//禁用用户交互
self.userInteractionEnabled = NO;
//隐藏title
[self setTitleColor:[UIColor clearColor] forState:UIControlStateNormal];
//执行代码块
self.clickBlock();
//开始动画
[UIView animateWithDuration:1.0 delay:0 usingSpringWithDamping:0.8 initialSpringVelocity:0.8 options:UIViewAnimationOptionLayoutSubviews animations:^{
//1.将矩形按钮缩成圆型
//改变圆角
self.layer.cornerRadius = self.deframe.size.height / 2.0;
self.layer.masksToBounds = YES;
//改变frame
self.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width - self.frame.size.height) / 2.0, self.frame.origin.y, self.frame.size.height, self.frame.size.height);
} completion:^(BOOL finished) {
//添加小弧线
[self.layer addSublayer:self.leftShape];
//显示小弧线
self.leftShape.hidden = NO;
//2.旋转圆形按钮
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
animation.toValue = @(M_PI * 7000);
animation.duration = 1000;
animation.beginTime = 0;
animation.fillMode = kCAFillModeBoth;
[self.layer addAnimation:animation forKey:nil];
}];
}
- (void)stopAnimateAndCallBack:(CallBack)callBack {
//移除旋转动画
[self.layer removeAllAnimations];
//隐藏小弧线
self.leftShape.hidden = YES;
//开始动画
[UIView animateWithDuration:1.0 delay:0 usingSpringWithDamping:0.8 initialSpringVelocity:0.8 options:UIViewAnimationOptionLayoutSubviews animations:^{
//3.将圆形按钮展开成矩形
//恢复最初圆角
self.layer.cornerRadius = self.cornerRadius;
self.layer.masksToBounds = YES;
//恢复最初frame
self.frame = self.deframe;
//显示title
[self setTitleColor:self.titleColor forState:UIControlStateNormal];
} completion:^(BOOL finished) {
//开启用户交互
self.userInteractionEnabled = YES;
//执行代码块
callBack();
}];
}
三.源码
源码放在了github上,欢迎指正,觉得不错的star一下呀!