客户端代码
- 点击小红心,发送socket给服务器,并且要传递房间Key给服务器,通知给哪个主播点赞,就能传入到对应的分组socket中
- 怎么传递房间key,房间Key在主播界面,一般一个客户端,只会产生一个房间,可以记录到socket对象中
- 业务逻辑:用户点击小红心,小红心就会往上慢慢飘。
- 实现原理:其实就是一个动画。
- 怎么实现:用UIView做不了,因为小红心是不规则的左右摆动,慢慢上去的。
- 可以使用核心动画(创建CALayer),CABasicAnimation和CAKeyframeAnimation,放在一个group组中。
- CABasicAnimation:渐渐显示动画,修改透明度
- CAKeyframeAnimation:做路径动画,描述小红心的路径,然后按照这个路径走.
- 动画完成,记得移除,可以用动画事务类,监听动画是否完成,代码一定要放在最前面
XMGLiveOverlayViewController.m
- (IBAction)clickUpvote:(id)sender {
// 发送点赞事件
[[SocketIOClient clientSocket] emit:@"upvote" with:@[[SocketIOClient clientSocket].roomKey]];
}
XMGUpVoteViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[[SocketIOClient clientSocket] on:@"upvote" callback:^(NSArray * _Nonnull data, SocketAckEmitter * _Nonnull ack) {
// 监听到点赞,进行点赞动画
[self setupVoteLayer];
}];
}
- (void)setupVoteLayer
{
CALayer *layer = [CALayer layer];
layer.contents = (id)[UIImage imageNamed:@"hearts (1)"].CGImage;
[self.view.layer addSublayer:layer];
layer.bounds = CGRectMake(0, 0, 30, 30);
layer.position = CGPointMake(self.view.width * 0.5, self.view.height);
[self setupAnim:layer];
}
- (void)setupAnim:(CALayer *)layer
{
[CATransaction begin];
[CATransaction setCompletionBlock:^{
[layer removeAllAnimations];
[layer removeFromSuperlayer];
}];
// 创建basic动画
CABasicAnimation *alphaAnim = [CABasicAnimation animation];
alphaAnim.keyPath = @"alpha";
alphaAnim.fromValue = @0;
alphaAnim.toValue = @1;
// 路径动画
CAKeyframeAnimation *pathAnim = [CAKeyframeAnimation animation];
pathAnim.keyPath = @"position";
pathAnim.path = [self animPath].CGPath;
// 创建动画组
CAAnimationGroup *group = [CAAnimationGroup animation];
group.animations = @[alphaAnim,pathAnim];
group.duration = 5;
[layer addAnimation:group forKey:nil];
[CATransaction commit];
}
- (UIBezierPath *)animPath
{
UIBezierPath *path = [UIBezierPath bezierPath];
CGFloat y = self.view.height;
CGFloat x = self.view.width * 0.5;
while (y > 0) {
x = arc4random_uniform(self.view.width - 20) + 20;
if (y == self.view.height) {
[path moveToPoint:CGPointMake(x, y)];
} else {
[path addLineToPoint:CGPointMake(x, y)];
}
y -= 20;
}
return path;
}
网友评论