UIScrollView的缩放原理解析

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

//  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变大,表示放大

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zok93

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值