将渐变应用于UIImage - 如何消除颜色反转? [英] Applying gradient to UIImage - how to remove color invertion?

查看:131
本文介绍了将渐变应用于UIImage - 如何消除颜色反转?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将渐变应用于 UIImage ,我希望它在底部变暗,然后在中间慢慢变为清晰或浅灰色。
大部分没关系,但我有一个问题,我的图像颜色在这个渐变下的某些地方反转。这看起来很烦人。我如何解决这个问题?

I'm applying gradient to UIImage, all i want it to be dark on the bottom and slowly turn to clear or light gray in the middle. It is mostly ok, but i have a problem that my image colors invert in some places under this gradient. This looks very annoying. How do i resolve that?

这是我方便的方法。

我尝试过选择不同的混合模式,但它没有帮助。另一个问题是,如何在底部使黑色更加密集?

I have tried picking different blending modes, but it doesn't help. Another question, is how do I make black more intensive in the bottom?

此方法无需任何额外代码即可使用。
起始颜色为 [UIColor blackColor] ,结束颜色为 [UIColor clearColor]

This method will work without any extra code. Start color is [UIColor blackColor] and end color is [UIColor clearColor] :

- (UIImage *)imageWithGradient:(UIImage *)img startColor:(UIColor *)color1 endColor:(UIColor *)color2 {
    UIGraphicsBeginImageContextWithOptions(img.size, NO, img.scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, 0, img.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    CGContextSetBlendMode(context, kCGBlendModeDarken); // tried normal here, same results


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

    // Create gradient
    NSArray *colors = [NSArray arrayWithObjects:(id)color1.CGColor, (id)color2.CGColor, nil];
    CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradient = CGGradientCreateWithColors(space, (__bridge CFArrayRef)colors, NULL);

    // Apply gradient
    CGContextClipToMask(context, rect, img.CGImage);
    CGContextDrawLinearGradient(context, gradient, CGPointMake(0,0), CGPointMake(0, img.size.height / 2.0), 0);
    UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    CGGradientRelease(gradient);
    CGColorSpaceRelease(space);

    return gradientImage;
}


推荐答案

试试这个
/ p>

Try this

// Set image over layer
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = imageView.frame;

// Add colors to layer
UIColor *centerColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.25];
UIColor *endColor = [UIColor grayColor];
gradient.colors = [NSArray arrayWithObjects:
                               (id)[endColor CGColor],
                               (id)[centerColor CGColor],
                               (id)[endColor CGColor],
                               nil];

[imageView.layer insertSublayer:gradient atIndex:0];

只需根据您的要求更改gradient.colors数组。

Just change array of gradient.colors depend on your requirements.

这篇关于将渐变应用于UIImage - 如何消除颜色反转?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆