您的位置:首页 > 产品设计 > UI/UE

UIScrollView的缩放原理解析

2016-08-07 00:04 204 查看

用代码创建一个可以缩放的图片

//  ViewController.m

#import "ViewController.h"

@interface ViewController ()<UIScrollViewDelegate>
@property(weak,nonatomic)UIImageView *imageView;
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIScrollView *scrollView = [[UIScrollView alloc] init];
// 设置scrollview大小为全屏 375*667(4.7吋屏幕)
scrollView.frame = self.view.bounds;
[self.view addSubview:scrollView];
scrollView.minimumZoomScale = 0.02;
scrollView.maximumZoomScale = 2;
// 启用代理
scrollView.delegate = self;

// 创建imageview对象,并且初始化的时候指定大小为图片的大小
UIImageView *imageView  = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ab179aaejw1f44f5h8np9j23402c0kjl"]];
[scrollView addSubview:imageView];
// 与属性关联
self.imageView = imageView;
// 设置可滚动范围为图片的大小
scrollView.contentSize = imageView.image.size;
// 设置界面刚显示出的时候,图片自带偏移
scrollView.contentOffset = CGPointMake(0, -64);
// 设置top留白64
scrollView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);

}
// 发生缩放时会调用
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return self.imageView;
}
@end


官方文档:To support zooming, you must set a delegate for your scroll view. The delegate object must conform to the UIScrollViewDelegate protocol. In many cases, the delegate will be the scroll view’s controller class. That delegate class must implement the viewForZoomingInScrollView: method and return the view to zoom. The implementation of the delegate method shown below returns the value of the controller’s imageView property, which is an instance of UIImageView. This specifies that the imageView property will be zoomed in response to zoom gestures, as well as any programmatic zooming.


大概意思说为了支持缩放,我们必须得遵守UIScrollViewDelegate协议。

很多情况下,委托都是滚动视图控制器类。

该委托类必须实现viewForZoomingInScrollView:方法并返回到缩放视图。

下面的委托方法的实现返回了imageView属性,它是实例是UIImageView 。

这里指定imageView属性将受到缩放的影响

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView

{
return self.imageView;
}


数据请点击此处参考上一篇文章的图片

缩放

一旦设置了 scrollView 的 delegate 并且实现了一个简单的代码,scrollView 就能够缩放了

这些代码的本质是在告诉 scrollView 去缩放谁

利用视图层次结构观察缩放后的 scrollView 和 imageView 的 position(center) 和 bounds 的变化

缩放结束后 scrollView 本身的 frame 并没有发生变化

缩放结束后 imageView 本身的 bounds 也没有发生变化

缩放结束后 imageView 的 center 发生了变化

在知道缩放谁了之后,scrollView会在内部通过修改 缩放目标 的 transfrom 实现缩放效果

so.发生缩放的时候,只会改变子控件的center的Position的x和y,通过改变x和y的大小来进行放大和缩小,x,y变大,表示放大
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: