Change View Alpha on Pan Gesture or Dragging

2019-06-02 15:02发布

I want to a UIView to drag to bottom of the screen on Pan Gesture but also the view alpha should scale down to "zero", when it reaches to the bottom of the screen.

And vise versa, when I will drag the view upwards then the UIView alpha should scale down to "1"

But the problem is that the view's alpha is scaling down to "Zero" on panning half of the screen or sometimes when I drag the view slower.
Initially I have made the UIView background color to Black.

I need to scale down the alpha of the view gradually , any idea or suggestion will be helpful.

  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条回答
倾城 Initia
2楼-- · 2019-06-02 15:38

I would look at the point on the screen you are currently at inside your handlePanGesture: find the percentage you are at on the view CGFloat percentage = nowPosition.y/self.view.frame.size.height; then set the alpha to that dimmer.alpha = 1.0 - percentage;. This way no matter where you are moving, you are setting the alpha to how close to the bottom you are.

查看更多
神经病院院长
3楼-- · 2019-06-02 15:41

You aren't scaling relative to your gesture; you're setting dimmer.alpha = 0.0037 every time handlePanGesture: executes, regardless of pan direction or distance.

-(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 !!!
}

A better implementation might look something like this:

-(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));
}
查看更多
登录 后发表回答