Reputation: 6692
I create a UIImage
from an NSAttributedString
:
UIFont *font = [UIFont systemFontOfSize:12.0f];
NSDictionary *attributes = @{NSFontAttributeName:font,
NSForegroundColorAttributeName:[UIColor greenColor]};
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:title attributes:attributes];
// Create the image here
UIImage *image = [self imageFromAttributedString:attributedString];
#pragma mark - Get image from attributed string
- (UIImage *)imageFromAttributedString:(NSAttributedString *)text
{
UIGraphicsBeginImageContextWithOptions(text.size, NO, 0.0);
// draw in context
[text drawAtPoint:CGPointMake(0.0, 0.0)];
// transfer image
UIImage *image = [UIGraphicsGetImageFromCurrentImageContext() imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
UIGraphicsEndImageContext();
return image;
}
My question is, what's the best way to create an image with the same text, but "reversed", i.e. [UIColor greenColor] with white font text?
Upvotes: 0
Views: 1205
Reputation: 2756
Use NSBackgroundColorAttributeName
to set background for green and NSForegroundColorAttributeName
the text to white.
The docs include:
NSString *const NSForegroundColorAttributeName;
NSString *const NSBackgroundColorAttributeName;
Upvotes: 1
Reputation: 1245
Once you have an image you can use Core Image Filters to reverse the colour or change blue to pink or red or whatever you wish: There is a CI Filter called CIColorInvert which will simply reverse the colours but personally I prefer using the colorMatrix filter which gives me more control code to reverse are the following:
Note this routine assumes your starting UIImage is beginImage the output is endImage
Using ColorMatrix:
CIFilter *filterci = [CIFilter filterWithName:@"CIColorMatrix" //rgreen
keysAndValues: kCIInputImageKey, beginImage, nil];
[filterci setValue:[CIVector vectorWithX:-1 Y:0 Z:0 W:0] forKey:@"inputRVector"]; // 5
[filterci setValue:[CIVector vectorWithX:0 Y:-1 Z:0 W:0] forKey:@"inputGVector"]; // 6
[filterci setValue:[CIVector vectorWithX:0 Y:0 Z:-1 W:0] forKey:@"inputBVector"]; // 7
[filterci setValue:[CIVector vectorWithX:0 Y:0 Z:0 W:1] forKey:@"inputAVector"]; // 8
[filterci setValue:[CIVector vectorWithX:0 Y:0 Z:0 W:0] forKey:@"inputBiasVector"];
CIImage *boutputImagei = [filterci outputImage];
CGImageRef cgimgi = [context createCGImage:boutputImagei fromRect:[boutputImage extent]];
UIImage *endImage = [UIImage imageWithCGImage:cgimgi];
CGImageRelease(cgimgi);
Using CIColorInvert:
CIFilter *filterci = [CIFilter filterWithName:@"CIColorInvert" //rgreen
keysAndValues: kCIInputImageKey, beginImage, nil];
CIImage *boutputImagei = [filterci outputImage];
CGImageRef cgimgi = [context createCGImage:boutputImagei fromRect:[boutputImage extent]];
UIImage *endImage = [UIImage imageWithCGImage:cgimgi];
CGImageRelease(cgimgi);
Upvotes: 0