3
votes

Is there a way to define a custom offset for a UIImage with aspect fill?

So currently aspect fill scales the image and centres it.

But I need a way to then define a offset, so I can manually adjust the image to fit even better.

Is this possible? I looked at the UIImage class but I couldn't find anything.

1

1 Answers

5
votes

I can't see a way to do this with a UIImageView by itself, but if you put it inside a containing view, set it to aspect fill, and then change the containing view's bounds, you can get your desired effect. Here's how I did it:

UIView *containingView = [[UIView alloc] initWithFrame:CGRectInset(self.view.bounds, 10, 10)];
containingView.clipsToBounds = YES;
[self.view addSubview:containingView];

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image"]];
imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.frame = containingView.bounds;
imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[containingView addSubview:imageView];

// Offset the image 100 pixels to the left
containingView.bounds = CGRectMake(100.0f, 0.0f, CGRectGetWidth(containingView.bounds), CGRectGetHeight(containingView.bounds));

Make sure that your imageView has clipsToBounds set to NO (the default) so that you can change containingView.bounds to pan around parts of the image that would otherwise be cropped off.

SWIFT 4+

let containerView = UIView(frame: view.bounds)
containerView.clipsToBounds = true
view.addSubview(containerView)

let imageView = UIImageView(image: image)
imageView.contentMode = .scaleAspectFill
imageView.frame = containerView.bounds
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
containerView.addSubview(imageView)

containerView.bounds = CGRect(x: imageXOffset,
                              y: imageYOffset,
                              width: containerView.bounds.width,
                              height: containerView.bounds.height)