Created
August 10, 2016 09:46
-
-
Save 6david9/d8051cda598d76f8d77c6b7b90939fa2 to your computer and use it in GitHub Desktop.
aspect fill image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (void)drawRect:(CGRect)rect | |
{ | |
if (!self.image) { | |
CGContextRef context = UIGraphicsGetCurrentContext(); | |
CGContextSetFillColorWithColor(context, self.backgroundColor.CGColor); | |
CGContextFillRect(context, rect); | |
return; | |
} | |
CGFloat w = CGRectGetWidth(self.frame); | |
CGFloat h = CGRectGetHeight(self.frame); | |
CGSize imageSize = self.image.size; | |
CGFloat widthScaleFactor = w / imageSize.width; | |
CGFloat heightScaleFactor = h / imageSize.height; | |
if (widthScaleFactor - heightScaleFactor < 0) { | |
CGFloat width = (imageSize.width / imageSize.height) * h; | |
CGFloat x = (w - width) / 2.0; | |
CGFloat y = 0.0; | |
[self.image drawInRect:CGRectMake(x, y, width, h)]; | |
} else { | |
CGFloat height = (imageSize.height / imageSize.width) * w; | |
CGFloat x = 0.0; | |
CGFloat y = (h - height) / 2.0; | |
[self.image drawInRect:CGRectMake(x, y, w, height)]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment