UIImage+Mask.m 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //
  2. // UIImage+Mask.m
  3. // Threema
  4. //
  5. // Copyright (c) 2013 Threema GmbH. All rights reserved.
  6. //
  7. #import "UIImage+Mask.h"
  8. #import "UIImage+Resize.h"
  9. @implementation UIImage (Mask)
  10. - (UIImage*) maskWithImage:(UIImage *)maskImage {
  11. if (maskImage == nil) {
  12. return nil;
  13. }
  14. CGImageRef maskRef = maskImage.CGImage;
  15. /* scale image to same size as mask */
  16. CGFloat maskImageRealWidth = roundf(maskImage.size.width * maskImage.scale);
  17. CGFloat maskImageRealHeight = roundf(maskImage.size.height * maskImage.scale);
  18. UIImage *scaledImage = [self resizedImageWithContentMode:UIViewContentModeScaleAspectFill
  19. bounds:CGSizeMake(maskImageRealWidth, maskImageRealHeight)
  20. interpolationQuality:kCGInterpolationDefault];
  21. CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
  22. CGImageGetHeight(maskRef),
  23. CGImageGetBitsPerComponent(maskRef),
  24. CGImageGetBitsPerPixel(maskRef),
  25. CGImageGetBytesPerRow(maskRef),
  26. CGImageGetDataProvider(maskRef), NULL, false);
  27. CGImageRef masked;
  28. if ((scaledImage.size.width != maskImageRealWidth) || (scaledImage.size.height != maskImageRealHeight)) {
  29. /* must crop */
  30. CGRect cropRect = CGRectMake(roundf((scaledImage.size.width - maskImageRealWidth) / 2), roundf((scaledImage.size.height - maskImageRealHeight) / 2), maskImageRealWidth, maskImageRealHeight);
  31. CGImageRef croppedImage = CGImageCreateWithImageInRect([scaledImage CGImage], cropRect);
  32. masked = CGImageCreateWithMask(croppedImage, mask);
  33. CGImageRelease(croppedImage);
  34. } else {
  35. masked = CGImageCreateWithMask([scaledImage CGImage], mask);
  36. }
  37. CGImageRelease(mask);
  38. UIImage *maskedImage = [UIImage imageWithCGImage:masked scale:maskImage.scale orientation:UIImageOrientationUp];
  39. CGImageRelease(masked);
  40. return maskedImage;
  41. }
  42. @end