Skip to content

Instantly share code, notes, and snippets.

@ksm
Created February 20, 2012 15:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ksm/1869823 to your computer and use it in GitHub Desktop.
Save ksm/1869823 to your computer and use it in GitHub Desktop.
CALayer draw resized image (kill all misaligned images)
/*
Source: Apple Developer - Understanding iOS View Compositing
*/
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
UIImage *image = [self loadImage];
if (image != nil) {
CGSize s = image.size;
CGRect r = layer.bounds;
CGFloat scale = MIN(r.size.width / s.width, r.size.height / s.height);
s.width *= scale; s.height *= scale;
r.origin.x += (r.size.width - s.width) * .5;
r.size.width = s.width;
r.origin.y += (r.size.height - s.height) * .5;
r.size.height = s.height;
CGContextSaveGState(ctx);
CGContextDrawImage(ctx, r, image.CGImage);
CGContextRestoreGState(ctx);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment