2011-02-28 2 views
5

2 вещи я хочу сделать, которые связаны:Как покрасить изображение/показать цвет?

  1. Показать блок любого цвета. Поэтому я могу изменить этот цвет на что-то еще в любое время.
  2. Оттенок UIImage отличается от другого. Здесь может работать наложение цвета с альфой, но сказать, что это изображение, имеющее прозрачный фон и не занимающее полный квадрат изображения.

Любые идеи?

ответ

10

Первый простой. Сделайте новый UIView и установите его цвет фона для любого цвета, который вам нужен.

Второй сложнее. Как вы уже упоминали, вы можете поместить новый вид поверх него с отключенной прозрачностью, но чтобы заставить его закрепить в тех же местах, вы хотите использовать маску. Что-то вроде этого:

UIImage *myImage = [UIImage imageNamed:@"foo.png"]; 

UIImageView *originalImageView = [[UIImageView alloc] initWithImage:myImage]; 
[originalImageView setFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)]; 
[parentView addSubview:originalImageView]; 

UIView *overlay = [[UIView alloc] initWithFrame:[originalImageView frame]]; 

UIImageView *maskImageView = [[UIImageView alloc] initWithImage:myImage]; 
[maskImageView setFrame:[overlay bounds]]; 

[[overlay layer] setMask:[maskImageView layer]]; 

[overlay setBackgroundColor:[UIColor redColor]]; 

[parentView addSubview:overlay]; 

Имейте в виду, вы должны будете #import <QuartzCore/QuartzCore.h> в файле реализации.

+0

Мне было трудно получить hori zontal, чтобы работать. Во-первых, я добавлял overlay в качестве подсмотра UITableViewCell, и центрирование терялось, когда ячейка изменялась. Я исправил это, добавив наложение как подпункт поля UILabel внутри ячейки, а не сам UITableViewCell. – bneely

+1

Вы также можете попробовать добавить его в 'contentView' ячейки таблицы. –

2

Простым способом достижения 1 является создание UILabel или даже UIView и изменение цвета backgroundColor по своему усмотрению.

Существует способ умножения цветов вместо их наложения, и это должно работать на 2. См. this tutorial.

11

Другой вариант, будет использовать методы категории на UIImage, как это ...

// Tint the image, default to half transparency if given an opaque colour. 
- (UIImage *)imageWithTint:(UIColor *)tintColor { 
    CGFloat white, alpha; 
    [tintColor getWhite:&white alpha:&alpha]; 
    return [self imageWithTint:tintColor alpha:(alpha == 1.0 ? 0.5f : alpha)]; 
} 

// Tint the image 
- (UIImage *)imageWithTint:(UIColor *)tintColor alpha:(CGFloat)alpha { 

    // Begin drawing 
    CGRect aRect = CGRectMake(0.f, 0.f, self.size.width, self.size.height); 
    UIGraphicsBeginImageContext(aRect.size); 

    // Get the graphic context 
    CGContextRef c = UIGraphicsGetCurrentContext(); 

    // Converting a UIImage to a CGImage flips the image, 
    // so apply a upside-down translation 
    CGContextTranslateCTM(c, 0, self.size.height); 
    CGContextScaleCTM(c, 1.0, -1.0); 

    // Draw the image 
    [self drawInRect:aRect]; 

    // Set the fill color space 
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
    CGContextSetFillColorSpace(c, colorSpace); 

    // Set the mask to only tint non-transparent pixels 
    CGContextClipToMask(c, aRect, self.CGImage); 

    // Set the fill color 
    CGContextSetFillColorWithColor(c, [tintColor colorWithAlphaComponent:alpha].CGColor); 

    UIRectFillUsingBlendMode(aRect, kCGBlendModeColor); 

    UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext();  

    // Release memory 
    CGColorSpaceRelease(colorSpace); 

    return img; 
} 
+0

это хорошо, но прозрачные пиксели тоже тонированы – zxcat

+2

1) Чтобы исправить также «прозрачные пиксели», добавьте 'CGContextClipToMask (c, aRect, self.CGImage);' перед 'UIRectFillUsingBlendMode'. 2) Чтобы применить истинный оттенок, сохраняя значения изображения, используйте kCGBlendModeColor. – Wienke

+1

Это отображает изображение в обратном порядке. После получения контекста необходимо добавить следующие строки: \t 'CGContextTranslateCTM (c, 0, self.size.height); CGContextScaleCTM (c, 1.0, -1.0); ' – chitza

-1

Попробуйте

- (void)viewDidLoad 
    { 
     [super viewDidLoad]; 
     UIView* maskedView = [self filledViewForPNG:[UIImage imageNamed:@"mask_effect.png"] 
               mask:[UIImage imageNamed:@"mask_image.png"] 
              maskColor:[UIColor colorWithRed:.6 green:.2 blue:.7 alpha:1]]; 


     [self.view addSubview:maskedView]; 

    } 

    -(UIView*)filledViewForPNG:(UIImage*)image mask:(UIImage*)maskImage maskColor:(UIColor*)maskColor 
    { 
     UIImageView *pngImageView = [[UIImageView alloc] initWithImage:image]; 
     UIImageView *maskImageView = [[UIImageView alloc] initWithImage:maskImage]; 

     CGRect bounds; 
     if (image) { 
      bounds = pngImageView.bounds; 
     } 
     else 
     { 
      bounds = maskImageView.bounds; 
     } 
     UIView* parentView = [[UIView alloc]initWithFrame:bounds]; 
     [parentView setAutoresizesSubviews:YES]; 
     [parentView setClipsToBounds:YES]; 

     UIView *overlay = [[UIView alloc] initWithFrame:bounds]; 
     [[overlay layer] setMask:[maskImageView layer]]; 
     [overlay setBackgroundColor:maskColor]; 

     [parentView addSubview:overlay]; 
     [parentView addSubview:pngImageView]; 
     return parentView; 
    } 
+0

Пожалуйста, объясните свой ответ. – hims056

4

Вот еще один способ реализации тонировка изображения, особенно если вы уже используя QuartzCore для чего-то другого.

Импорт QuartzCore:

#import <QuartzCore/QuartzCore.h>  

Создать прозрачную CALayer и добавить его в качестве подслоя для изображения, которое вы хотите отлив:

CALayer *sublayer = [CALayer layer]; 
[sublayer setBackgroundColor:[UIColor whiteColor].CGColor]; 
[sublayer setOpacity:0.3]; 
[sublayer setFrame:toBeTintedImage.frame]; 
[toBeTintedImage.layer addSublayer:sublayer]; 

Добавить QuartzCore к вашим проектам список Framework (если он ISN» t уже есть), в противном случае вы получите такие ошибки компилятора:

Undefined symbols for architecture i386: "_OBJC_CLASS_$_CALayer" 
Смежные вопросы