Подтвердить что ты не робот

IOS: создать более темную версию UIImage и оставить прозрачные пиксели неизменными?

Я нашел

Создайте новый UIImage, добавив тень к существующему UIImage

и

UIImage, есть простой способ сделать его темнее или черным

Но выбранные ответы не работают для меня.

У меня есть UIImage, в котором могут быть прозрачные пиксели, мне нужно создать новый UIImage с непрозрачными пикселями, затемненными, есть ли способ сделать это? Я думал об использовании UIBezierPath, но я не знаю, как это сделать только для непрозрачных пикселей.

4b9b3361

Ответ 1

Это класс, который я использую для цветных изображений, даже если они прозрачны.

+ (UIImage *)colorizeImage:(UIImage *)image withColor:(UIColor *)color {
    UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGRect area = CGRectMake(0, 0, image.size.width, image.size.height);

    CGContextScaleCTM(context, 1, -1);
    CGContextTranslateCTM(context, 0, -area.size.height);

    CGContextSaveGState(context);
    CGContextClipToMask(context, area, image.CGImage);

    [color set];
    CGContextFillRect(context, area);

    CGContextRestoreGState(context);

    CGContextSetBlendMode(context, kCGBlendModeMultiply);

    CGContextDrawImage(context, area, image.CGImage);

    UIImage *colorizedImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return colorizedImage;
}

Чтобы затемнить изображение, вы передадите метод черный или серый UIColor с пониженной прозрачностью.

Ответ 2

Как пробовать фильтр CoreImage?

Вы можете использовать фильтр CIColorControls для настройки яркости входа и контраста, чтобы затемнить изображение.

CIContext *context = [CIContext contextWithOptions:nil];
CIImage *inputImage = [[CIImage alloc] initWithImage:sourceImage]; //your input image

CIFilter *filter= [CIFilter filterWithName:@"CIColorControls"];
[filter setValue:inputImage forKey:@"inputImage"];
[filter setValue:[NSNumber numberWithFloat:0.5] forKey:@"inputBrightness"];

// Your output image
UIImage *outputImage = [UIImage imageWithCGImage:[context createCGImage:filter.outputImage fromRect:filter.outputImage.extent]];

Подробнее о параметрах CIFilter читайте здесь:

http://developer.apple.com/library/mac/#documentation/graphicsimaging/reference/CoreImageFilterReference/Reference/reference.html%23//apple_ref/doc/filter/ci/CIColorControls

Ответ 3

Здесь быстрая версия Swift, использующая CIExposureAdjust CIFilter:)

  // Get the original image and set up the CIExposureAdjust filter
  guard let originalImage = UIImage(named: "myImage"),
    let inputImage = CIImage(image: originalImage),
    let filter = CIFilter(name: "CIExposureAdjust") else { return }

  // The inputEV value on the CIFilter adjusts exposure (negative values darken, positive values brighten)
  filter.setValue(inputImage, forKey: "inputImage")
  filter.setValue(-2.0, forKey: "inputEV")

  // Break early if the filter was not a success (.outputImage is optional in Swift)
  guard let filteredImage = filter.outputImage else { return }

  let context = CIContext(options: nil)
  let outputImage = UIImage(CGImage: context.createCGImage(filteredImage, fromRect: filteredImage.extent))

  myImageView.image = outputImage // use the filtered UIImage as required.