iOS导航栏*缩放头像效果

时间:2022-11-27 07:43:39

效果图:

iOS导航栏*缩放头像效果

上代码:

先给一个self.navigationItem.titleView ,然后再放个ImangeView添加到titleView上:

   UIView *titleView = [[UIView alloc] init];
self.navigationItem.titleView = titleView; self.headImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"timg.jpg"]];
self.headImageView.frame = CGRectMake(, , , );
self.headImageView.layer.cornerRadius = ;
self.headImageView.layer.masksToBounds = YES;
//保证头像水平居中
self.headImageView.center = CGPointMake(titleView.center.x, );
[titleView addSubview:self.headImageView];

核心代码:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGFloat scale = 1.0;
NSLog(@"y======%.2f---top======%.2f",scrollView.contentOffset.y,scrollView.contentInset.top);
CGFloat offsetY = scrollView.contentOffset.y + scrollView.contentInset.top;
NSLog(@"offsetY=======%.2f",offsetY); if (offsetY < ) { // 放大
// 允许下拉放大的最大距离为330
// 1.5是放大的最大倍数
// 这个值可以*调整
scale = MIN(1.5, - offsetY / );
} else if (offsetY > ) { // 缩小
// 允许向上超过导航条缩小的最大距离为330
// 为了防止缩小过度,给一个最小值为0.50
scale = MAX(0.50, - offsetY / );
} self.headImageView.transform = CGAffineTransformMakeScale(scale, scale); // 保证缩放后y坐标不变
CGRect frame = self.headImageView.frame;
frame.origin.y = -self.headImageView.layer.cornerRadius / ;
self.headImageView.frame = frame; }

Demo地址:https://github.com/domanc/HeadImageScale.git