четверг, 6 февраля 2014 г.

Маленькие полезности. Часть 1

  
  Доброго времени суток) Решил немного расслабиться и написать несколько коротких, но полезных статеек. В последнее время, часто сталкиваюсь в надобности написания достаточно простых функций, которых по странному стечению обстоятельств не присутствуют в ios sdk.

  И так  -  первым делом поговорим о цвете :)

Преобразование из HEX в UIColor
 // преобразование из hex в UIColor  
 -(UIColor *)getHexColor:(NSString*)hex  
 {  
   NSString *newString = nil;  
   if ([hex hasPrefix:@"#"])  
   {  
     newString = [hex substringFromIndex:1];  
   }  
   else if([hex hasPrefix:@"0x"])  
   {  
     newString = [hex substringFromIndex:2];  
   }  
   if([hex length] ==6)  
     newString = hex;  
   if ([newString length] !=6)  
   {  
     return [UIColor clearColor];  
   }  
   NSRange range;  
   range.location = 0;  
   range.length = 2;  
   NSString *rString = [newString substringWithRange:range];  
   range.location = 2;  
   NSString *gString = [newString substringWithRange:range];  
   range.location = 4;  
   NSString *bString = [newString substringWithRange:range];  
   unsigned int r, g, b;  
   [[NSScanner scannerWithString:rString] scanHexInt:&r];  
   [[NSScanner scannerWithString:gString] scanHexInt:&g];  
   [[NSScanner scannerWithString:bString] scanHexInt:&b];  
   UIColor * colorWave = [UIColor colorWithRed:((float) r / 255.0f)  
                      green:((float) g / 255.0f)  
                      blue:((float) b / 255.0f)  
                      alpha:1.0f];  
   NSDictionary * dict = @{@"colorHex": hex,  
               @"UIColor":colorWave};  
   [_colors addObject:dict];  
   return colorWave;  
 }  


Соответственно и обратное преобразование
Преобразование из UIColor в HEX
 // преобразование из hex в UIColor  
 -(UIColor *)getHexColor:(NSString*)hex  
 {  
   NSString *newString = nil;  
   if ([hex hasPrefix:@"#"])  
   {  
     newString = [hex substringFromIndex:1];  
   }  
   else if([hex hasPrefix:@"0x"])  
   {  
     newString = [hex substringFromIndex:2];  
   }  
   if([hex length] ==6)  
     newString = hex;  
   if ([newString length] !=6)  
   {  
     return [UIColor clearColor];  
   }  
   NSRange range;  
   range.location = 0;  
   range.length = 2;  
   NSString *rString = [newString substringWithRange:range];  
   range.location = 2;  
   NSString *gString = [newString substringWithRange:range];  
   range.location = 4;  
   NSString *bString = [newString substringWithRange:range];  
   unsigned int r, g, b;  
   [[NSScanner scannerWithString:rString] scanHexInt:&r];  
   [[NSScanner scannerWithString:gString] scanHexInt:&g];  
   [[NSScanner scannerWithString:bString] scanHexInt:&b];  
   UIColor * colorWave = [UIColor colorWithRed:((float) r / 255.0f)  
                      green:((float) g / 255.0f)  
                      blue:((float) b / 255.0f)  
                      alpha:1.0f];  
   NSDictionary * dict = @{@"colorHex": hex,  
               @"UIColor":colorWave};  
   [_colors addObject:dict];  
   return colorWave;  
 }  

Изменение цвета картинки(UIImage)
P.S. лучше всего использовать белую картинку
 // смена цвета картинки  
 +(UIImage*) imageNamed:(NSString*)imageName WithColor:(UIColor*) color{  
   UIImage *img = [UIImage imageNamed:imageName];  
   UIGraphicsBeginImageContext(img.size);  
   CGContextRef context = UIGraphicsGetCurrentContext();  
   [color setFill];  
   CGContextTranslateCTM(context, 0, img.size.height);  
   CGContextScaleCTM(context, 1.0, -1.0);  
   CGRect rect = CGRectMake(0, 0, img.size.width, img.size.height);  
   CGContextDrawImage(context, rect, img.CGImage);  
   CGContextClipToMask(context, rect, img.CGImage);  
   CGContextAddRect(context, rect);  
   CGContextDrawPath(context,kCGPathFill);  
   UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();  
   UIGraphicsEndImageContext();  
   return coloredImg;  
 }  

А так же последние две функции, позволяющие изменять оттенки цвета - светлее/темнее
 // Цвет ярче  
 + (UIColor *)lighterColorForColor:(UIColor *)c  
 {  
   CGFloat r, g, b, a;  
   if ([c getRed:&r green:&g blue:&b alpha:&a])  
     return [UIColor colorWithRed:MIN(r + 0.2, 1.0)  
                 green:MIN(g + 0.2, 1.0)  
                 blue:MIN(b + 0.2, 1.0)  
                 alpha:a];  
   return nil;  
 }  
 // Цвет темнее  
 + (UIColor *)darkerColorForColor:(UIColor *)c  
 {  
   CGFloat r, g, b, a;  
   if ([c getRed:&r green:&g blue:&b alpha:&a])  
     return [UIColor colorWithRed:MAX(r - 0.2, 0.0)  
                 green:MAX(g - 0.2, 0.0)  
                 blue:MAX(b - 0.2, 0.0)  
                 alpha:a];  
   return nil;  
 }  

На сегодня все) В следующий раз поговрим о работе со строками. Всем удачи!

Комментариев нет :

Отправить комментарий