开发者

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

I want to take an objective-c UIImage and make it all black, but still have the same alpha values so that it beco开发者_StackOverflowmes 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜