手势拖动. 约束图片边缘 .限制拉动范围
@implementation WDEnterLineViewController{ float xx; float yy; UIImageView *bgImgView; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. [self createLayout]; } -(void)createLayout{ bgImgView = [[UIImageView alloc]init]; UIImage *image = [UIImage imageNamed:@"110"]; bgImgView.image = image; CGImageRef imageRef = [image CGImage]; CGSize size = CGSizeMake(CGImageGetWidth(imageRef), CGImageGetHeight(imageRef)); xx = size.width; yy = size.height; WDLog(@"%f====%f",xx,yy); [self.view addSubview:bgImgView]; [bgImgView mas_makeConstraints:^(MASConstraintMaker *make) { make.centerX.equalTo(self.view.mas_centerX); make.centerY.equalTo(self.view.mas_centerY); make.width.offset(size.width); make.height.offset(size.height); }]; [self addGestureRecognizerToView:bgImgView]; //如果处理的是图片. [bgImgView setUserInteractionEnabled:YES]; [bgImgView setMultipleTouchEnabled:YES]; } // 添加手势 - (void) addGestureRecognizerToView:(UIView *)view { // 移动手势 UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panView:)]; [view addGestureRecognizer:panGestureRecognizer]; } // 处理拖拉手势 - (void) panView:(UIPanGestureRecognizer *)panGestureRecognizer { UIView *view = panGestureRecognizer.view; if (panGestureRecognizer.state == UIGestureRecognizerStateBegan || panGestureRecognizer.state == UIGestureRecognizerStateChanged) { CGPoint translation = [panGestureRecognizer translationInView:view.superview]; [view setCenter:(CGPoint){view.center.x + translation.x, view.center.y + translation.y}]; [panGestureRecognizer setTranslation:CGPointZero inView:view.superview]; }else if(panGestureRecognizer.state == UIGestureRecognizerStateEnded){ WDLog(@"-centerX:%f===centerY:%f",bgImgView.center.x,bgImgView.center.y); WDLog(@"%f====%f",self.view.center.x,self.view.center.y) CGPoint point = CGPointMake(bgImgView.center.x, bgImgView.center.y); if (point.x >= xx / 2) { point.x = xx / 2; }; if (point.x <= self.view.center.x - (xx - APP_WIDTH) / 2) { point.x = self.view.center.x - (xx - APP_WIDTH) / 2; }; if (point.y >= yy / 2 + 64) { point.y = yy / 2 + 64; }; if (point.y <= self.view.center.y - (yy - APP_HEIGHT) / 2) { point.y = self.view.center.y - (yy - APP_HEIGHT) / 2; }; bgImgView.center = point; } }
让明天,不后悔今天的所作所为
posted on 2017-08-10 11:41 Sinner_Yun 阅读(586) 评论(0) 编辑 收藏 举报