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

Change View Alpha on Pan Gesture or Dragging

我想要一个 UIView 在 Pan Gesture 上拖动到屏幕底部,但当它到达屏幕底部时,视图 alpha 应该缩小到 "zero"。

反之亦然,当我将视图向上拖动时,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;
    }

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

-(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));
}

我会查看您当前在屏幕上的点 handlePanGesture: 找到您在视图中所处的百分比 CGFloat percentage = nowPosition.y/self.view.frame.size.height; 然后将 alpha 设置为 dimmer.alpha = 1.0 - percentage; .这样,无论您移动到哪里,都可以将 alpha 设置为离底部有多近。