Insets to UIImageView?

It looks like you want to have a touchable imageView, so why not using an UIButton with image and imageEdgeInsets?

UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
[b setFrame:someFrame];
[b setImage:img forState:UIControlStateNormal];
b.imageEdgeInsets = UIEdgeInsetsMake(20, 20, 20, 20);
[b addTarget:self action:@selector(imageClicked:) forControlEvents:UIControlEventTouchUpInside];

Using the method given here :

UIImage *image= [MyUtil imageWithImage:[UIImage imageNamed:@"MyImage"] scaledToSize:CGSizeMake(80, 80)];

UIImageView* imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
imgView.contentMode = UIViewContentModeCenter;
[imgView setImage:image];

Now your insets become 100-80 i.e. 20 .

This is a workaround to provide insets to an UIImageView. Better answers are welcomed.


You can add inset to UIImage instead of UIImageView.

Swift 4

let imageView = UIImageView() 
imageView.contentMode = .scaleAspectFill
imageView.image = UIImage(named: "example")?.withAlignmentRectInsets(UIEdgeInsets(top: -4, left: 0, bottom: -4, right: 0))

My Code

  • minus inset: smaller image
  • plus inset: larger image

Swift4

private lazy var imageView: UIImageView = {
    let view = UIImageView()
    view.contentMode = .scaleAspectFit
    let insetValue: CGFloat = -8
    view.image = image.withAlignmentRectInsets(UIEdgeInsets(top: insetValue, left: insetValue, bottom: insetValue, right: insetValue))
    return view
}()