UIImage Aspect Bias Offset

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

Thus, currently the size aspect fills the image and centers it.

But I need a way to determine the offset, so I can manually adjust the image to be even better.

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


source to share

1 answer

I don't see a way to do this with the UIImageView itself, but if you put it inside the containing view, set the aspect fill for it, and then change the bounds of the containing view, you can get the desired effect. This is 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 your imageView is set to clipsToBounds of NO (the default) so you can change the containingView.bounds to pan around parts of the image that would otherwise be cropped.


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

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

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




All Articles