Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a UIImageView darker when highlighted (tapped)?

I have a UIImageView that shows a picture. When tapped and held, I'd like it to darken as long as the user has their finger over the imageview. Basically, I want it to act like a UIButton.

I currently have it do this with a UIGestureRecognizer:

- (void)viewDidLoad
{
    [super viewDidLoad];

    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]
                                         initWithTarget:self
                                         action:@selector(pictureViewTapped)];
    singleTap.numberOfTapsRequired = 1;
    singleTap.numberOfTouchesRequired = 1;
    [self.pictureImageView addGestureRecognizer:singleTap];
    [self.pictureImageView setUserInteractionEnabled:YES];
}

and in my pictureViewTapped, I have this (for now):

- (void)pictureViewTapped {
    NSLog(@"Picture view was tapped!");
}

How do I make the UIImageView darker? Any help is appreciated.

like image 287
swiftcode Avatar asked May 12 '13 18:05

swiftcode


2 Answers

Easiest way is to use layers in the QuartzCore framework:

add: QuartzCore.framework to project in your project settings add to .h file: #import

create gesture for long press instead of tap as that behaviors as you described:

 self.longTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(darkenImage)];
    [self.imageView setUserInteractionEnabled:YES];
    [self.imageView addGestureRecognizer:self.longTap];

method called when gesture active:

-(void)darkenImage {
    switch (self.longTap.state) {
        case UIGestureRecognizerStateBegan: // object pressed
        case UIGestureRecognizerStateChanged:
            [self.imageView.layer setBackgroundColor:[UIColor blackColor].CGColor];
            [self.imageView.layer setOpacity:0.9];
            break;
        case UIGestureRecognizerStateEnded: // object released
            [self.imageView.layer setOpacity:1.0];
            break;
        default: // unknown tap
            NSLog(@"%i", self.longTap.state);
            break;
    }
}
like image 90
Shams Ahmed Avatar answered Nov 15 '22 04:11

Shams Ahmed


In my case, background will show through when set ImageView's layer opacity to 0.9.

I use solution that use new layer.

let coverLayer = CALayer()
coverLayer.frame = imageView.bounds;
coverLayer.backgroundColor = UIColor.blackColor().CGColor
coverLayer.opacity = 0.0
imageView.layer.addSublayer(coverLayer)

// when tapped
coverLayer.opacity = 0.1
like image 20
Daishi Nakajima Avatar answered Nov 15 '22 06:11

Daishi Nakajima