开发中遇到个类似脑图的一个东西,里面需要支持缩放,下面介绍一下我是怎么处理的
需要的类
UIPinchGestureRecognizer 这个就是缩放的手势
过程
1.将视图添加缩放手势
UIView *customView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchView:)];
[customView addGestureRecognizer:pinchGestureRecognizer];
相应方法
#define MaxSCale 2.0 //最大缩放比例
#define MinScale 0.5 //最小缩放比例
@property (nonatomic,assign) CGFloat totalScale; //<? 用于记录视图即时的缩放比例
// 处理缩放手势
- (void)pinchView:(UIPinchGestureRecognizer *)pinchGestureRecognizer
{
UIView *view = pinchGestureRecognizer.view;
CGFloat scale = pinchGestureRecognizer.scale;
//放大情况
if(scale > 1.0){
if(self.totalScale > MaxSCale) return;
}
//缩小情况
if (scale < 1.0) {
if (self.totalScale < MinScale) return;
}
if (pinchGestureRecognizer.state == UIGestureRecognizerStateBegan || pinchGestureRecognizer.state == UIGestureRecognizerStateChanged) {
view.transform = CGAffineTransformScale(view.transform, pinchGestureRecognizer.scale, pinchGestureRecognizer.scale);
pinchGestureRecognizer.scale = 1;
self.totalScale *=scale;
}
}
总结
最开始,并没有想好怎么限制,后来参考别人的办法,就是在处理手势的时候 适当的时候return。
值得注意的是self.totalScale一定要初始化为 1;
网友评论