Search This Blog

Wednesday, December 29, 2010

Generating runtime image in iPhone/ iPad

input color in int.

+ (UIImage *)shapeCircle:(int)color {

// create the bitmap context
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(nil,30,30,8,0, colorSpace,kCGImageAlphaPremultipliedLast);
CFRelease(colorSpace);

// set the fill color
//CGColorRef fillColor = [[UIColor blackColor] CGColor];
NSString *hexColor = [NSString stringWithFormat:@"%x", color];
hexColor = [[@"" stringByPaddingToLength:6 - [hexColor length] withString:@"0" startingAtIndex:0] stringByAppendingString:hexColor];
float r = [self hexToColorValue:[hexColor substringToIndex:2]];
float g = [self hexToColorValue:[hexColor substringWithRange:NSMakeRange(2, 2)]];
float b = [self hexToColorValue:[hexColor substringFromIndex:4]];

//fillColor = [[[UIColor alloc] initWithRed:1 green:0 blue:0 alpha:1] CGColor];
//CGContextSetFillColor(context, CGColorGetComponents(fillColor));
CGContextSetRGBFillColor(context, r, g, b, 1);
CGContextAddArc(context, 15.0f, 15.0f, 12.0f, 0, 360 * M_PI/180, 1);
CGContextFillPath(context);

//CGContextSetFillColor(context, CGColorGetComponents([[UIColor whiteColor] CGColor]));
CGContextSetRGBFillColor(context, 1, 1, 1, 1);
CGContextAddArc(context, 15.0f, 15.0f, 6.0f, 0, 360 * M_PI/180, 1);
CGContextFillPath(context);

// convert the context into a CGImageRef
CGImageRef imageRef = CGBitmapContextCreateImage(context);
CGContextRelease(context);
UIImage *image = [[UIImage alloc] initWithCGImage:imageRef];
CGImageRelease(imageRef);

return [image autorelease];
}

+ (float)hexToColorValue:(NSString *)color {
NSScanner* scanner = nil;
unsigned int cInt;
scanner = [NSScanner scannerWithString:color];
[scanner scanHexInt:&cInt];
return (float)cInt / 255;
}

No comments: