Skip to content

Instantly share code, notes, and snippets.

@sdrew
Created September 1, 2011 05:48
Show Gist options
  • Select an option

  • Save sdrew/1185537 to your computer and use it in GitHub Desktop.

Select an option

Save sdrew/1185537 to your computer and use it in GitHub Desktop.

Revisions

  1. @marcoarment marcoarment created this gist Jul 23, 2011.
    57 changes: 57 additions & 0 deletions gistfile1.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    // Usage example:
    // input image: http://f.cl.ly/items/3v0S3w2B3N0p3e0I082d/Image%202011.07.22%2011:29:25%20PM.png
    //
    // UIImage *buttonImage = [UIImage ipMaskedImageNamed:@"UIButtonBarAction.png" color:[UIColor redColor]];

    // .h
    @interface UIImage (IPImageUtils)
    + (UIImage *)ipMaskedImageNamed:(NSString *)name color:(UIColor *)color;
    @end

    // .m
    @implementation UIImage (IPImageUtils)

    + (UIImage *)ipMaskedImageNamed:(NSString *)name color:(UIColor *)color
    {
    UIImage *blackWithAlphaImage = [UIImage imageNamed:name];
    CGSize size = blackWithAlphaImage.size;

    UIGraphicsBeginImageContextWithOptions(size, YES, blackWithAlphaImage.scale);
    [[UIColor whiteColor] setFill];

    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    CGContextFillRect(UIGraphicsGetCurrentContext(), rect);
    [blackWithAlphaImage drawInRect:rect];
    UIImage *compositedMaskImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    CGSize unscaledSize = size;
    unscaledSize.width *= blackWithAlphaImage.scale;
    unscaledSize.height *= blackWithAlphaImage.scale;

    UIGraphicsBeginImageContext(unscaledSize);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [color setFill];

    CGRect unscaledRect = CGRectMake(0, 0, unscaledSize.width, unscaledSize.height);
    CGContextFillRect(context, unscaledRect);
    UIImage *colorImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    CGImageRef compositedMaskImageRef = compositedMaskImage.CGImage;
    CGImageRef mask = CGImageMaskCreate(
    unscaledSize.width,
    unscaledSize.height,
    CGImageGetBitsPerComponent(compositedMaskImageRef),
    CGImageGetBitsPerPixel(compositedMaskImageRef),
    CGImageGetBytesPerRow(compositedMaskImageRef),
    CGImageGetDataProvider(compositedMaskImageRef),
    NULL,
    false
    );

    CGImageRef masked = CGImageCreateWithMask([colorImage CGImage], mask);
    return [UIImage imageWithCGImage:masked scale:compositedMaskImage.scale orientation:UIImageOrientationUp];
    }

    @end