在scrollViewDidScroll代理方法里计算子控件距离中心点的差值,再用transform放大该子控件,越接近中心点放大比例越高
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if (scrollView == _myScrollView) {
int centerX = scrollView.contentOffset.x + scrollView.frame.size.width / 2;
for (UIImageView *imageV in _imageViews) {
CGFloat distanceX = fabs(imageV.center.x - centerX); // 子控件距中心点差值
if (distanceX < imageV.frame.size.width / 2) {
// 0-1,差值越小(越靠近中心点),distanceScale越大
CGFloat distanceScale = 1 - (distanceX / (imageV.frame.size.width / 2));
// 设置中心子控件缩放比例,这里设置最多放大1.2倍,所以用1 + 0.2 * 差值比例
CGFloat currentScale = 1 + distanceScale * 0.2;
imageV.transform = CGAffineTransformMakeScale(currentScale, currentScale);
[_myScrollView bringSubviewToFront:imageV];
}
}
}
}
完整代码:
#import "ViewController.h"
@interface ViewController () <UIScrollViewDelegate>
@property (nonatomic, strong) UIScrollView *myScrollView;
@property (nonatomic, strong) NSMutableArray *imageViews;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self initSubviews];
}
- (void)initSubviews {
_myScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 200, [UIScreen mainScreen].bounds.size.width, 220)];
_myScrollView.backgroundColor = UIColor.lightGrayColor;
_myScrollView.delegate = self;
_myScrollView.contentSize = CGSizeMake(20 + 180 * 10, 0);
_myScrollView.clipsToBounds = NO;
_imageViews = [NSMutableArray array];
for (int i = 0; i < 10; i++) {
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(20 + i * 180, 20, 160, 180)];
imageView.backgroundColor = [self randomColor];
imageView.userInteractionEnabled = YES;
[_myScrollView addSubview:imageView];
[_imageViews addObject:imageView];
}
[self.view addSubview:_myScrollView];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if (scrollView == _myScrollView) {
int centerX = scrollView.contentOffset.x + scrollView.frame.size.width / 2;
for (UIImageView *imageV in _imageViews) {
CGFloat distanceX = fabs(imageV.center.x - centerX); // 子控件距中心点差值
if (distanceX < imageV.frame.size.width / 2) {
// 0-1,差值越小(越靠近中心点),distanceScale越大
CGFloat distanceScale = 1 - (distanceX / (imageV.frame.size.width / 2));
// 设置中心子控件缩放比例,这里设置最多放大1.2倍,所以用1 + 0.2 * 差值比例
CGFloat currentScale = 1 + distanceScale * 0.2;
imageV.transform = CGAffineTransformMakeScale(currentScale, currentScale);
[_myScrollView bringSubviewToFront:imageV];
}
}
}
}
- (UIColor *)randomColor {
NSInteger aRedValue = arc4random() % 255;
NSInteger aGreenValue = arc4random() % 255;
NSInteger aBlueValue = arc4random() % 255;
UIColor *randColor = [UIColor colorWithRed:aRedValue / 255.0f green:aGreenValue / 255.0f blue:aBlueValue / 255.0f alpha:1.0f];
return randColor;
}
@end