Skip to content

Instantly share code, notes, and snippets.

@6david9
Created August 10, 2016 09:46
Show Gist options
  • Save 6david9/d8051cda598d76f8d77c6b7b90939fa2 to your computer and use it in GitHub Desktop.
Save 6david9/d8051cda598d76f8d77c6b7b90939fa2 to your computer and use it in GitHub Desktop.
aspect fill image
- (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