Search code examples
uiviewuiswipegesturerecognizer

UISwipeGestureRecognizer control brightness


I'm looking to create a UISwipeGestureRecognizer which is attached to my UIView. What I want to achieve allows the user to swipe their finger across the screen and set the brightness of the screen.

Here is what I've attempted:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint currentPosition = [touch locationInView:self.view];

    CGFloat deltaXX = (startPoint.x - currentPosition.x);

    float brightVal;

    if (deltaXX > 0) {
        brightVal = [[UIScreen mainScreen] brightness] / ((startPoint.x / deltaXX) * 1.0);
    } else {
        brightVal = [[UIScreen mainScreen] brightness] - ((startPoint.x / deltaXX) * 1.0);
    }

    NSLog(@"%f", brightVal);
    [[UIScreen mainScreen] setBrightness:brightVal];
}

However this doesn't seem to work properly. At the right hand edge of the screen, the user can quickly adjust their brightness.

I think the problem is I can't work out how to normalize the value where 1.0 would be the left hand side and 0.0 would be the right hand side.

Any suggestions?


Solution

  • You cannot normalize unless you have a total. In this case this would by your screen width. It is counter-intuitive to have the screen get brighter faster if you start more on the right. It would be better to determine the equivalent of any point to the brightness scale:

    CGFloat width = self.view.bounds.size.width;
    brightVal = position.x / width; 
    

    Now, if startVal is larger than the brightness the brightness should jump to the point on the scale after the move starts. This is pretty much how a UISlider works. You don't even need to calculate the delta to the start point.

    You could have this be triggered only after deltaXX is beyond a certain threshold.