1、CAScrollLayer的简介
CAScrollLayer用于显示一个滑动图层的一部分,可以确定滑动方向和可视区域面积,限制不滑出区域外!相关属性如下:其中
/* Scroll the contents of the layer to ensure that rect 'r' is visible. */- (void)scrollToRect:(CGRect)r;
不是很理解,只做自己的见解!
#importNS_ASSUME_NONNULL_BEGINCA_CLASS_AVAILABLE (10.5, 2.0, 9.0, 2.0)@interface CAScrollLayer : CALayer//改变layer的原点位置到指定点- (void)scrollToPoint:(CGPoint)p;//改变layer的可视区域和原点限制 r: CGRectMake(x, y, width, height)//1、layer的bounds:{ {x1, y1}, {width1, height1}}, 原点限制x1<=x && y1<=y//2、如果layer的width >= width1,height >= height1,原点移动到指定位置就不能滑动//如果with
2、CAScrollLayer的简单使用
CALayer *contentLayer = [CALayer layer]; contentLayer.backgroundColor = [UIColor whiteColor].CGColor; contentLayer.contents = (id)[UIImage imageNamed:@"pic1.jpg"].CGImage; contentLayer.frame = CGRectMake(0, 0, CScreenWidth, 300); CAScrollLayer *scrollLayer = [CAScrollLayer layer]; scrollLayer.frame = CGRectMake(50, 50, CScreenWidth-100,200); [scrollLayer addSublayer:contentLayer]; scrollLayer.scrollMode = kCAScrollBoth; scrollLayer.backgroundColor = [UIColor redColor].CGColor; [self.showView.layer addSublayer:scrollLayer];// scrollLayer.masksToBounds = NO;//默认是YES,改为NO自己可能好懂些 self.layer = scrollLayer; [self.showView addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)]];- (void)panGesture:(UIPanGestureRecognizer *)pan{ CGPoint trans = [pan translationInView:self.showView]; CGPoint ori =self.layer.bounds.origin; ori = CGPointMake(ori.x-trans.x, ori.y-trans.y); [self.layer scrollPoint:ori]; [self.layer scrollToRect:CGRectMake(-50, -50, 100, 100)]; NSLog(@"=======%@",NSStringFromCGRect([self.layer visibleRect])); [pan setTranslation:CGPointZero inView:self.showView];}
(1)原点(-50,-50),所以最大的时候左边和上面有50的距离,最小可视区域宽高是(-50+100,-50+100)
效果图
[self.layer scrollToRect:CGRectMake(-50, -50, 100, 100)]
(2)原点(0,0),所以最大的时候左边和上面有0的距离,最小可视区域宽高是(0+100,0+100)
[self.layer scrollToRect:CGRectMake(0, 0, 100, 100)]
(3)原点(100,100),所以最大的时候左边和上面可以移动100的距离,最小可视区域宽高是(100+214,100+100)
scrollLayer.masksToBounds = YES;
scrollLayer.masksToBounds = NO;
[self.layer scrollToRect:CGRectMake(100, 100, 214, 100)]
(4)不设置scrollTpRect效果图
常用的是第三种,使大图layer滑动不会到边界外面!