Skip to content

Instantly share code, notes, and snippets.

@CreatureSurvive
Last active October 29, 2018 21:46
Show Gist options
  • Save CreatureSurvive/62eefc65e44c365532a482ea1d0f685b to your computer and use it in GitHub Desktop.
Save CreatureSurvive/62eefc65e44c365532a482ea1d0f685b to your computer and use it in GitHub Desktop.
A couple simple methods of scaling a UIView transform to fit inside another UIView.
/*
/ usage:
/ UIView * myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 375, 375)];
/ UIView * myContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
/ CGFloat scale = [self scaleForSize:myView.bounds.size fitToSize:myContainer.bounds.size];
/ myView.transform = CGAffineTransformScale(CGAffineTransformIdentity, scale, scale);
/ [myContainer addSubview:myView];
*/
- (CGFloat)scaleForSize:(CGSize)source fitToSize:(CGSize)destination {
CGFloat scale = 1;
scale = (destination.width / source.width);
if (source.height * scale > destination.height) {
scale = destination.height / source.height;
}
return scale;
}
/*
/ usage:
/ UIView * myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 375, 375)];
/ UIView * myContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
/ myContainer = [self scaleView:myView toFitInView:myContainer];
/ [myContainer addSubview:myView];
*/
- (UIView *)scaleView:(UIView *)source toFitInView:(UIView *)destination {
CGFloat scale = 1;
scale = (destination.bounds.size.width / source.bounds.size.width);
if (source.bounds.size.height * scale > destination.bounds.size.height) {
scale = destination.bounds.size.height / source.bounds.size.height;
}
source.transform = CGAffineTransformScale(CGAffineTransformIdentity, scale, scale);
return source;
}
/*
/ usage:
/ UIView * myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 375, 375)];
/ UIView * myContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
/ [self addScaledSubview:myView toView:myContainer];
*/
- (void)addScaledSubview:(UIView *)source toView:(UIView *)destination {
CGFloat scale = 1;
scale = (destination.bounds.size.width / source.bounds.size.width);
if (source.bounds.size.height * scale > destination.bounds.size.height) {
scale = destination.bounds.size.height / source.bounds.size.height;
}
source.transform = CGAffineTransformScale(CGAffineTransformIdentity, scale, scale);
[destination addSubview:source];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment