Наложение UIImage с цветом? - PullRequest
16 голосов
/ 10 мая 2009

Я пытаюсь добавить черное наложение поверх некоторых текущих UIImage (которые белого цвета). Я пытался использовать следующий код:

[[UIColor blackColor] set];
[image drawAtPoint:CGPointMake(0, 0) blendMode:kCGBlendModeOverlay alpha:1.0];

Но это не работает, и я почти уверен, что сет не должен быть там.

Ответы [ 9 ]

53 голосов
/ 08 мая 2014

Итак, для суммирования всех ответов в один вот метод вставки, который отлично работает от iOS 6 до iOS 11 со всеми видами изображений и иконок:

+ (UIImage *)filledImageFrom:(UIImage *)source withColor:(UIColor *)color{

    // begin a new image context, to draw our colored image onto with the right scale
    UIGraphicsBeginImageContextWithOptions(source.size, NO, [UIScreen mainScreen].scale);

    // get a reference to that context we created
    CGContextRef context = UIGraphicsGetCurrentContext();

    // set the fill color
    [color setFill];

    // translate/flip the graphics context (for transforming from CG* coords to UI* coords
    CGContextTranslateCTM(context, 0, source.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    CGContextSetBlendMode(context, kCGBlendModeColorBurn);
    CGRect rect = CGRectMake(0, 0, source.size.width, source.size.height);
    CGContextDrawImage(context, rect, source.CGImage);

    CGContextSetBlendMode(context, kCGBlendModeSourceIn);
    CGContextAddRect(context, rect);
    CGContextDrawPath(context,kCGPathFill);

    // generate a new UIImage from the graphics context we drew onto
    UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    //return the color-burned image
    return coloredImg;
}

Обновление: Версия Swift 3

func filledImage(source: UIImage, fillColor: UIColor) -> UIImage {

    UIGraphicsBeginImageContextWithOptions(source.size, false, UIScreen.main.scale)

    let context = UIGraphicsGetCurrentContext()
    fillColor.setFill()

    context!.translateBy(x: 0, y: source.size.height)
    context!.scaleBy(x: 1.0, y: -1.0)

    context!.setBlendMode(CGBlendMode.colorBurn)
    let rect = CGRect(x: 0, y: 0, width: source.size.width, height: source.size.height)
    context!.draw(source.cgImage!, in: rect)

    context!.setBlendMode(CGBlendMode.sourceIn)
    context!.addRect(rect)
    context!.drawPath(using: CGPathDrawingMode.fill)

    let coloredImg : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()

    return coloredImg
}
31 голосов
/ 11 мая 2009

Вы хотите закрепить контекст за маской изображения, а затем залить сплошным цветом:

- (void)drawRect:(CGRect)rect
{
    CGRect bounds = [self bounds];
    [[UIColor blackColor] set];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClipToMask(context, bounds, [myImage CGImage]);
    CGContextFillRect(context, bounds);
}

Примечание: myImage должна быть переменной экземпляра, которая содержит UIImage. Я не уверен, берет ли она маску из альфа-канала или интенсивность, поэтому попробуйте оба.

11 голосов
/ 27 сентября 2010

Я только что написал учебник, который поможет с этим. Мой подход дает вам копию UIImage с изменениями цвета, которые вы хотите. Подход rpetrich великолепен, но требует создания подкласса. Мой подход - это всего лишь несколько строк кода, которые можно вставить туда, где они вам нужны. http://coffeeshopped.com/2010/09/iphone-how-to-dynamically-color-a-uiimage

NSString *name = @"badge.png";
UIImage *img = [UIImage imageNamed:name];

// begin a new image context, to draw our colored image onto
UIGraphicsBeginImageContext(img.size);

// get a reference to that context we created
CGContextRef context = UIGraphicsGetCurrentContext();

// set the fill color
[color setFill];

// translate/flip the graphics context (for transforming from CG* coords to UI* coords
CGContextTranslateCTM(context, 0, img.size.height);
CGContextScaleCTM(context, 1.0, -1.0);

// set the blend mode to color burn, and the original image
CGContextSetBlendMode(context, kCGBlendModeColorBurn);
CGRect rect = CGRectMake(0, 0, img.size.width, img.size.height);
CGContextDrawImage(context, rect, img.CGImage);

// set a mask that matches the shape of the image, then draw (color burn) a colored rectangle
CGContextClipToMask(context, rect, img.CGImage);
CGContextAddRect(context, rect);
CGContextDrawPath(context,kCGPathFill);

// generate a new UIImage from the graphics context we drew onto
UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

//return the color-burned image
return coloredImg;
8 голосов
/ 06 июля 2014

Начиная с iOS 7, существует гораздо более простое решение:

UIImage* im = [UIImage imageNamed:@"blah"];
im = [im imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[[UIColor blackColor] setFill];
[im drawInRect:rect];
8 голосов
/ 16 мая 2012

Посмотрите на этот метод

 + (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)size;
    {
      UIImage *img = nil;

      CGRect rect = CGRectMake(0, 0, size.width, size.height);
      UIGraphicsBeginImageContext(rect.size);
      CGContextRef context = UIGraphicsGetCurrentContext();
      CGContextSetFillColorWithColor(context,
                                     color.CGColor);
      CGContextFillRect(context, rect);
      img = UIGraphicsGetImageFromCurrentImageContext();

      UIGraphicsEndImageContext();

      return img;
    }
3 голосов
/ 22 июля 2009

В дополнение к решению от rpetrich (что, кстати, здорово - помогите мне великолепно), вы также можете заменить строку CGContextClipToMask на:

    CGContextSetBlendMode(context, kCGBlendModeSourceIn); //this is the main bit!

Это режим смешивания SourceIn, который выполняет маскировку цвета тем, что находится в GetCurrentContext.

1 голос
/ 05 декабря 2016

Вот как вы это делаете с Swift 3.0 и с использованием расширений UIImage. Супер просто.

public extension UIImage {
    func filledImage(fillColor: UIColor) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.main.scale)

        let context = UIGraphicsGetCurrentContext()!
        fillColor.setFill()

        context.translateBy(x: 0, y: self.size.height)
        context.scaleBy(x: 1.0, y: -1.0)

        context.setBlendMode(CGBlendMode.colorBurn)

        let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
        context.draw(self.cgImage!, in: rect)

        context.setBlendMode(CGBlendMode.sourceIn)
        context.addRect(rect)
        context.drawPath(using: CGPathDrawingMode.fill)

        let coloredImg : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()

        return coloredImg
    }
}

Затем для запуска просто сделайте:

let image = UIImage(named: "image_name").filledImage(fillColor: UIColor.red)
0 голосов
/ 23 марта 2019

Вы можете сделать это программно в Swift 4.x следующим образом:

imageView.image = UIImage(named: "imageName")?.withRenderingMode(.alwaysTemplate)
imageView.tintColor = .purple
0 голосов
/ 10 мая 2009

-set используется для установки цвета последующих операций рисования, которые не включают блики. Я предлагаю в качестве первого вызова отобразить еще один (пустой) UIView поверх вашего UIImageView и установить его цвет фона:

myView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.5];

Очевидно, вы должны использовать желаемые значения белого и альфа.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...