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.
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;
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With