简体   繁体   中英

Change View Alpha on Pan Gesture or Dragging

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM