在平移手势或拖动时更改视图Alpha

时间:2015-01-21 17:57:10

标签: ios objective-c uiview

我希望UIView在Pan Gesture上拖动到屏幕的底部,但是当它到达屏幕底部时,视图alpha应缩小到“零”。

反之亦然,当我向上拖动视图时,UIView alpha应缩小为“1”

但问题是视图的alpha会在平移屏幕的一半时缩小到“Zero”,或者有时当我慢慢拖动视图时。 最初我将UIView背景颜色设为黑色。

我需要逐渐缩小视图的alpha值,任何想法或建议都会有所帮助。

  UIPanGestureRecognizer * panner = nil;
    panner = [[UIPanGestureRecognizer alloc] initWithTarget: self action:@selector(handlePanGesture:)];
    [self.view addGestureRecognizer:panner ];
    [panner setDelegate:self];
    [panner release];


    CGRect frame = CGRectMake(0, 0, 320, 460);
    self.dimmer = [[UIView alloc] initWithFrame:frame];
    [self.dimmer setBackgroundColor:[UIColor blackColor]];
    [self.view addSubview:dimmer];



     -(IBAction) handlePanGesture:(UIPanGestureRecognizer *) sender {

      static CGPoint lastPosition = {0}; 
      CGPoint nowPosition; float alpha = 0.0;
      float new_alpha = 0.0;

        nowPosition = [sender translationInView: [self view]];
         alpha = [dimmer alpha] -0.0037;
         dimmer.alpha -=alpha;
    }

2 个答案:

答案 0 :(得分:5)

我会在您handlePanGesture:内的屏幕上查看您在视图CGFloat percentage = nowPosition.y/self.view.frame.size.height;上找到的百分比,然后将该字母设置为dimmer.alpha = 1.0 - percentage;。这样,无论你在哪里移动,你都要将alpha设置为接近底部的位置。

答案 1 :(得分:-1)

你没有相对于你的手势进行缩放;无论平移方向或距离如何,每次执行dimmer.alpha = 0.0037时都会设置handlePanGesture:

-(IBAction) handlePanGesture:(UIPanGestureRecognizer *) sender {
  static CGPoint lastPosition = {0}; 
  CGPoint nowPosition;
  float alpha = 0.0;
  float new_alpha = 0.0; // Unused!!

  nowPosition = [sender translationInView: [self view]]; // Unused!!
  alpha = [dimmer alpha] - 0.0037;
  dimmer.alpha -= alpha; // === dimmer.alpha = dimmer.alpha - (dimmer.alpha - 0.0037)
                         // === dimmer.alpha = 0.0037 !!!
}

更好的实现可能如下所示:

-(IBAction) handlePanGesture:(UIPanGestureRecognizer *) sender {
  CGPoint nowPosition = [sender translationInView: [self view]];
  CGFloat alpha = dimmer.alpha - ([sender translationInView: [self view]].y)/320.0;
  dimmer.alpha = MAX(0, MIN(1, alpha));
}