UIImage, is there an easy way to make it darker or

2019-08-28 21:11发布

问题:

I want to take an objective-c UIImage and make it all black, but still have the same alpha values so that it becomes a silhouette of its former image. I was wondering is there any more convenient way to do this than just taking the CGImage data and changing the values for each pixel?

回答1:

You can extract the alpha info by creating a CGBitmapContext with kCGImageAlphaOnly, and 1 component and draw into that. Then you'd have an image with alpha only.

Then you could composite that onto an entirely black image with kCGBlendModeDestinationIn. That should leave you with an image that's all black with the original alpha values.



回答2:

Here is a function I have used to make a colorized version of an image:

@interface NSImage( ColorizedImageAdditions )

- (NSImage*) colorizedImage: (NSColor*) color;

@end

- (NSImage*) colorizedImage: (NSColor*) color
{
    NSSize imageSize = [ self size ];
    NSImage* result = [ [ [ NSImage alloc ] initWithSize: imageSize ] autorelease ];

    [ result lockFocus ];
    [ NSGraphicsContext saveGraphicsState ];

    NSRect imageBounds = NSMakeRect( 0, 0, imageSize.width, imageSize.height );

    [ color setFill ];
    [ NSBezierPath fillRect: imageBounds ];

    [ self drawInRect: imageBounds fromRect: NSZeroRect 
            operation: NSCompositeDestinationIn fraction: 1.0 ];

    [ NSGraphicsContext restoreGraphicsState ];
    [ result unlockFocus ];

    return result;
}

It utilizes the NSCompositeDestinationIn operation to fill in opaque areas of the image with the desired color.