UIImage+Scaling.m 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /*****************************************************************************
  2. * UIImage+Scaling.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2015 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Felix Paul Kühne <fkuehne # videolan.org>
  9. *
  10. * Refer to the COPYING file of the official project for license.
  11. *****************************************************************************/
  12. #import <UIKit/UIKit.h>
  13. #import "UIImage+Scaling.h"
  14. #import <AVFoundation/AVFoundation.h>
  15. @implementation UIImage (Scaling)
  16. + (UIImage *)scaleImage:(UIImage *)image toFitRect:(CGRect)rect
  17. {
  18. CGRect destinationRect = AVMakeRectWithAspectRatioInsideRect(image.size, rect);
  19. CGImageRef cgImage = image.CGImage;
  20. size_t bitsPerComponent = CGImageGetBitsPerComponent(cgImage);
  21. size_t bytesPerRow = CGImageGetBytesPerRow(cgImage);
  22. CGColorSpaceRef colorSpaceRef = CGImageGetColorSpace(cgImage);
  23. CGBitmapInfo bitmapInfoRef = CGImageGetBitmapInfo(cgImage);
  24. CGContextRef contextRef = CGBitmapContextCreate(NULL,
  25. destinationRect.size.width,
  26. destinationRect.size.height,
  27. bitsPerComponent,
  28. bytesPerRow,
  29. colorSpaceRef,
  30. bitmapInfoRef);
  31. CGContextSetInterpolationQuality(contextRef, kCGInterpolationLow);
  32. CGContextDrawImage(contextRef, (CGRect){CGPointZero, destinationRect.size}, cgImage);
  33. return [UIImage imageWithCGImage:CGBitmapContextCreateImage(contextRef)];
  34. }
  35. @end