2

I have a layout as below. Image view inside a view that takes half of view controller (white one). Image view fills container considering some margins on the top and bottom. I have scale mode on the image view set to aspect fit. All this gives me the the exact visual effect I want.

enter image description here

However I have also tap gesture recognizer installed on the image view, and I want it to detect taps only on the area where actual image is displayed (due to aspect fit it takes only a part of available space). The image itself will be dynamically changed so that I don't know what aspect ratio it's going to have. What would be the easiest way to achieve this?

I guess I would have to get rid of traililnig and leading constraints on the image view, but what next?

Wujo
  • 1,845
  • 2
  • 25
  • 33
  • 1
    You'll want to [calculate the frame that the image occupies within the image view](http://stackoverflow.com/a/35510271/2976878) and then only respond to taps within that rect. – Hamish Apr 06 '16 at 11:38
  • Yeah, calculating if the tap is within the area of the image was my first idea. However I counted on some easier solution as this seems to be quite common problem. But if there is no better option... – Wujo Apr 06 '16 at 11:53

2 Answers2

0

After set the UIImage of UIImageView update the frame of UIImageView as per image.

How to make UIImageView automatically resize to the size of the image loaded

Check above link.

Community
  • 1
  • 1
Payal Maniyar
  • 4,293
  • 3
  • 25
  • 51
0

First, find the size of image and then update frame of ImageView. Set x and y position according to size of image and requirement.

UIImageView *myImageView = [[UIImageView alloc]init];
UIImage *img = [UIImage imageNamed:@"draft"];

CGSize mySize = [img size];

CGRect newFrame=CGRectMake(0, 0, mySize.width, mySize.height);
NSLog(@"height  : %f  width : %f",mySize.height,mySize.width);

myImageView.frame = newFrame;
myImageView.image = img;
ElGavilan
  • 6,610
  • 16
  • 27
  • 36
Ketan Parmar
  • 27,092
  • 9
  • 50
  • 75
  • Not exactly. This way the image won't fit the container. However it's quite easy to calculate the proper size but I was hoping for avoiding modifying the frame programatically. – Wujo Apr 06 '16 at 12:24
  • 1
    you have to update frame. there is no other option. if you want to keep image in center then use (self.view.frame.size.width/2) - (imageView.frame.size.width/2) as value of x and set y accordingly. – Ketan Parmar Apr 06 '16 at 12:43
  • Ok, thanks. In this case I will rather calculate if the tap is within area of the actual image and leave the trailing and leading margins. – Wujo Apr 06 '16 at 13:00
  • yeah, you can try that also...! – Ketan Parmar Apr 06 '16 at 13:14