Как программно изменить оттенок UIImage?
Я очень новичок в обработке изображений. Я должен реализовать эффект оттенка в моем проекте приложения iPhone. Поэтому мне нужно изменить оттенок UIImage
. Пожалуйста, предоставьте мне какой-либо примерный код или ссылку для этого учебника.
Заранее спасибо
Ответы
Ответ 1
Во-первых, вам нужно решить, создаете ли вы фиксированный оттенок или вращаете существующий оттенок. Примеры обоих приведены ниже.
![Hue changes]()
Фиксированный оттенок
Фиксирование оттенка можно выполнить с помощью стандартных инструментов рисования - просто убедитесь, что режим наложения установлен на kCGBlendModeHue
, и рисуйте с соответствующим оттенком. Это происходит из решения Nitish, хотя я обнаружил, что для saturation
меньше 1.0
были несогласованные результаты. Этот метод позволяет варьировать альфа, но для истинного насыщения, отличного от 100%, вам, вероятно, понадобится второй раунд рисования.
- (UIImage*) imageWithImage:(UIImage*) source fixedHue:(CGFloat) hue alpha:(CGFloat) alpha;
// Note: the hue input ranges from 0.0 to 1.0, both red. Values outside this range will be clamped to 0.0 or 1.0.
{
// Find the image dimensions.
CGSize imageSize = [source size];
CGRect imageExtent = CGRectMake(0,0,imageSize.width,imageSize.height);
// Create a context containing the image.
UIGraphicsBeginImageContext(imageSize);
CGContextRef context = UIGraphicsGetCurrentContext();
[source drawAtPoint:CGPointMake(0,0)];
// Draw the hue on top of the image.
CGContextSetBlendMode(context, kCGBlendModeHue);
[[UIColor colorWithHue:hue saturation:1.0 brightness:1 alpha:alpha] set];
UIBezierPath *imagePath = [UIBezierPath bezierPathWithRect:imageExtent];
[imagePath fill];
// Retrieve the new image.
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return result;
}
Вращающийся оттенок
Чтобы повернуть оттенок, вам нужны фильтры Core Image. Код ниже преобразует UIImage в CIImage, а затем преобразует результат обратно в UIImage для отображения. В зависимости от того, откуда происходит ваше изображение, вы можете избежать одного или обоих этих шагов.
Удобно, что самый первый пример в Руководство по программированию основных изображений: использование фильтров основных изображений использует фильтр CIHueAdjust.
// #import <CoreImage/CoreImage.h>
// Partially from https://developer.apple.com/library/mac/#documentation/graphicsimaging/conceptual/CoreImaging/ci_tasks/ci_tasks.html
- (UIImage*) imageWithImage:(UIImage*) source rotatedByHue:(CGFloat) deltaHueRadians;
{
// Create a Core Image version of the image.
CIImage *sourceCore = [CIImage imageWithCGImage:[source CGImage]];
// Apply a CIHueAdjust filter
CIFilter *hueAdjust = [CIFilter filterWithName:@"CIHueAdjust"];
[hueAdjust setDefaults];
[hueAdjust setValue: sourceCore forKey: @"inputImage"];
[hueAdjust setValue: [NSNumber numberWithFloat: deltaHueRadians] forKey: @"inputAngle"];
CIImage *resultCore = [hueAdjust valueForKey: @"outputImage"];
// Convert the filter output back into a UIImage.
// This section from http://stackoverflow.com/a/7797578/1318452
CIContext *context = [CIContext contextWithOptions:nil];
CGImageRef resultRef = [context createCGImage:resultCore fromRect:[resultCore extent]];
UIImage *result = [UIImage imageWithCGImage:resultRef];
CGImageRelease(resultRef);
return result;
}
Ответ 2
- (void) changeToHue:(float)hue saturation:(float)saturation {
UIGraphicsBeginImageContext(self.bounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();
UIView *hueBlend = [[UIView alloc] initWithFrame:self.bounds];
hueBlend.backgroundColor = [UIColor colorWithHue:hue saturation:saturation brightness:1 alpha:1];
CGContextDrawImage(context, self.bounds, self.image.CGImage);
CGContextSetBlendMode(context, kCGBlendModeHue);
[hueBlend.layer renderInContext:context];
self.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
Ответ 3
Взять Dondragmer отличный пример фиксированного оттенка в качестве отправной точки. Вот моя модификация, чтобы устранить проблему с прозрачными областями, заданными с тем же оттенком.
- (UIImage*) imageWithImage:(NSString *)name fixedHue:(CGFloat) hue alpha:(CGFloat) alpha;
// Note: the hue input ranges from 0.0 to 1.0, both red. Values outside this range will be clamped to 0.0 or 1.0.
{
UIImage *source = [UIImage imageNamed:name];
// Find the image dimensions.
CGSize imageSize = [source size];
CGRect imageExtent = CGRectMake(0,0,imageSize.width,imageSize.height);
// Create a context containing the image.
UIGraphicsBeginImageContext(imageSize);
CGContextRef context = UIGraphicsGetCurrentContext();
[source drawAtPoint:CGPointMake(0,0)];
// Setup a clip region using the image
CGContextSaveGState(context);
CGContextTranslateCTM(context, 0, source.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextClipToMask(context, imageExtent, source.CGImage);
//[[UIColor colorWithHue:hue saturation:1.0 brightness:1 alpha:alpha] set];
CGContextFillRect(context, imageExtent);
// Draw the hue on top of the image.
CGContextDrawImage(context, imageExtent, source.CGImage);
CGContextSetBlendMode(context, kCGBlendModeHue);
[[UIColor colorWithHue:hue saturation:1.0 brightness:1 alpha:alpha] set];
UIBezierPath *imagePath = [UIBezierPath bezierPathWithRect:imageExtent];
[imagePath fill];
CGContextRestoreGState(context); // remove clip region
// Retrieve the new image.
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return result;
}
Благодаря:
Как изменить оттенок UIIMAGE с прозрачной областью?
CGContextClipToMask UIImage Mask Инвертировать вверх и вниз
Ответ 4
В блоге Apple Swift я наткнулся на это приложение для фильтрации фотографий: https://developer.apple.com/swift/blog/?id=16
Ниже приведен пример кода, отредактированного для создания содержащегося метода, который возвращает UIImage со случайным оттенком.
func applyHue(source: UIImage) -> UIImage {
// Create a place to render the filtered image
let context = CIContext(options: nil)
// Create an image to filter
let inputImage = CIImage(image: source)
// Create a random color to pass to a filter
let randomColor = [kCIInputAngleKey: (Double(arc4random_uniform(314)) / 100)]
// Apply a filter to the image
let filteredImage = inputImage!.imageByApplyingFilter("CIHueAdjust", withInputParameters: randomColor)
// Render the filtered image
let renderedImage = context.createCGImage(filteredImage, fromRect: filteredImage.extent)
// Return a UIImage
return UIImage(CGImage: renderedImage)
}
Ответ 5
Быстрая версия вращающегося кода Dondragmer выше
// Convert the filter output back into a UIImage.
// This section from http://stackoverflow.com/a/7797578/1318452
func imageWithImage(source: UIImage, rotatedByHue: CGFloat) -> UIImage {
// Create a Core Image version of the image.
let sourceCore = CIImage(CGImage: source.CGImage)
// Apply a CIHueAdjust filter
let hueAdjust = CIFilter(name: "CIHueAdjust")
hueAdjust.setDefaults()
hueAdjust.setValue(sourceCore, forKey: "inputImage")
hueAdjust.setValue(CGFloat(rotatedByHue), forKey: "inputAngle")
let resultCore = hueAdjust.valueForKey("outputImage") as CIImage!
let context = CIContext(options: nil)
let resultRef = context.createCGImage(resultCore, fromRect: resultCore!.extent())
let result = UIImage(CGImage: resultRef)
return result!
}