- 这里我们主要是用一下,如何能保持原来的图片的宽高比来轻松的实现放大的效果,主要的是UIViewContentModeScaleAspectFill这个起的效果:
- 我们用tableView来展示这个效果吧
- 我们这里并没有计算图片的宽高比,直接用UIViewContentModeScaleAspectFill来实现
#import "ViewController.h"
const CGFloat ZYTopViewH = 350;
@interface ViewController ()
@property(nonatomic,weak)UIImageView *topView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.contentInset = UIEdgeInsetsMake(ZYTopViewH * 0.5, 0, 0, 0);
UIImageView *topView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"biaoqingdi"]];
topView.frame = CGRectMake(0, -ZYTopViewH, 375, ZYTopViewH);
topView.contentMode = UIViewContentModeScaleAspectFill;
[self.tableView insertSubview:topView atIndex:0];
self.topView = topView;
}
- 实现tableView的数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 20;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
}
cell.textLabel.text = [NSString stringWithFormat:@"test---%zd",indexPath.row];
return cell;
}
- 最后用scrollViewDidScroll来监听拖动事件
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGFloat offsetY = scrollView.contentOffset.y;
CGFloat offsetH = -ZYTopViewH * 0.5 - offsetY;
if (offsetH < 0) return;
CGRect frame = self.topView.frame;
frame.size.height = ZYTopViewH + offsetH;
self.topView.frame = frame;
}
看一下效果:
这里主要是讲UIViewContentModeScaleAspectFill的作用,但是我觉得这个demo中也牵扯到一些东西,也顺便讲讲
- 为什么将UIImageView采用
[self.tableView insertSubview:topView atIndex:0];
这种方式来添加,其实一开始我也是直接让UIImageView作为headerView的,但是作为headerView的话,就不能让图片一开始显示一部分在外面了,也不好控制
- 然后偏移量等,就自然而然的想到了。多尝试,就多收获。。。。
时间: 2024-08-25 15:56:11