iOS 用代码绘制三级渐变背景色 CAGradientLayer / CGContextDrawLinearGradient

这一切源于最新的需求,
某个 view 的背景色要求是渐变色,
不是两种颜色渐变,
而是三种颜色,
不是从左到右,
而是左上角到右下角。

总有产品经理想害朕~~
但作为一个乐观向上并且很帅的程序猿要勇于接受出题人的挑战😁。


# 苹果爸爸提供的 api 不知如何翻译好 就叫做可变尺寸方法吧

- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets NS_AVAILABLE_IOS(5_0);
- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode NS_AVAILABLE_IOS(6_0); // the interior is resized according to the resizingMode

这两个差不多的,第二个比第一个多了拉伸方式

参数解释:

  • capInsets:受保护的区域,就是去拉伸,平铺其他元素,不要动我,我是大熊猫。
  • resizingMode:拉伸模式,平铺还是拉伸

对于渐进色的话这种截图拉伸的方式比较单一也比较二,基本难以满足产品需求。
而我的需求是左上角到右下角的三段颜色渐变,厉害了我的产品~
所以我们来想想其它方式。
看了这个蛋疼的 api 我想选择死亡。


# CAGradientLayer

这个类是 CALayer 的一个子类,可以简单方便地生成颜色渐变的图层。

/* The gradient layer draws a color gradient over its background color,
filling the shape of the layer (i.e. including rounded corners). */

看这个类的介绍感觉我觉得人生重新充满了希望。

看下参数:
colors:你要的颜色,数组
locations:[0 - 1] 单调梯度增加,就是上面每个颜色的区间值,不给定默认均匀分布
startPoint:开始点
endPoint:结束点

开始点和结束点这两个参数对于我的需求比较重要,看下解释:

/* The start and end points of the gradient when drawn into the layer's
coordinate space. The start point corresponds to the first gradient
stop, the end point to the last gradient stop. Both points are
defined in a unit coordinate space that is then mapped to the
layer's bounds rectangle when drawn. (I.e. [0,0] is the bottom-left
corner of the layer, [1,1] is the top-right corner.) The default values
are [.5,0] and [.5,1] respectively. Both are animatable. */

解释的很明确了,简单地说就是这个图的样子,可以简便的控制方向,是从左到右还是从右到左还是左上角到右下角。

By BarneyZhaoooo

type:没有卵用,目前没的选择。

通过实践,几行代码愉快地实现产品需求。

    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    
    gradientLayer.colors = @[(__bridge id)[UIColor redColor].CGColor,
                             (__bridge id)[UIColor yellowColor].CGColor,
                             (__bridge id)[UIColor blueColor].CGColor];
    
    gradientLayer.locations = @[@0.2,
                                @0.4,
                                @1.0];// 区间
    
    gradientLayer.startPoint = CGPointMake(0,
                                           0);// 开始点
    
    gradientLayer.endPoint = CGPointMake(1,
                                         1);// 结束点
    
    gradientLayer.frame = CGRectMake(0,
                                     100,
                                     SCREEN_WIDTH,
                                     200);
    
    [self.view.layer addSublayer:gradientLayer];

当然这是通过加 layer 的方式,在渲染中对于性能的消耗还需要自行考虑。

仿佛有种发廊的感觉,很魔性

# 利用 Core Graphics 的实现

这是比较底层的 c 的方式,理论上可以绘制好多好多东西,用在本需求上有些大材小用,不过并不影响我们学习。

思路是:拿到上下文 - 做图 - 获取图片

比较重要的概念就是上下文,也就是 context ,为什么翻译成上下文我不是太理解,第一次看到这几个字是完全懵逼的,反正知道就是拿到绘制图片的二进制编码就对了。

如何获取上下文。

CGContextRef context = UIGraphicsGetCurrentContext(); // 获取当前图形的上下文

You should call this function only when a bitmap-based graphics context is the current graphics context.
If the current context is nil or was not created by a call to UIGraphicsBeginImageContext, this function returns nil.

要注意使用此方法时图片一定是由 UIGraphicsBeginImageContext 创建的,否贼这个方法会返回 nil

另一个重要方法:告诉系统我要开始做图啦~

void UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale);

参数的含义:
size : 要创建的图片的尺寸
opaque : 背景是否为不透明, YES 图片背景将会是黑色
scale : 缩放比例,传入0则表示让图片的缩放因子根据屏幕的分辨率而变化,我们早已离 iOS 4.0的年代远去,传0就好。

CGContextDrawLinearGradient 实现线性渐变的方法

当然它还有兄弟方法 CGContextDrawRadialGradient 弧度渐变

/* Fill the current clipping region of `context' with a linear gradient from
   `startPoint' to `endPoint'. The location 0 of `gradient' corresponds to
   `startPoint'; the location 1 of `gradient' corresponds to `endPoint';
   colors are linearly interpolated between these two points based on the
   values of the gradient's locations. The option flags control whether the
   gradient is drawn before the start point or after the end point. */

CG_EXTERN void CGContextDrawLinearGradient(CGContextRef cg_nullable c,
    CGGradientRef cg_nullable gradient, CGPoint startPoint, CGPoint endPoint,
    CGGradientDrawingOptions options)
    CG_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0);

有了生成图片的方法还不够,我最后想要设置的是背景色

这个就比较简单了,UIKit 很常见的 api

+ (UIColor *)colorWithPatternImage:(UIImage *)image

嗯,这个没什么好说了。


# 准备就绪,可以开始了,Talk is cheap,show me the code.

考虑了大部分需要用到的情况

typedef NS_ENUM(NSUInteger, GradientType) {// 渐变方向
    GradientTypeTopToBottom      = 0,//从上到下
    GradientTypeLeftToRight      = 1,//从左到右
    GradientTypeUpleftToLowright = 2,//左上到右下
    GradientTypeUprightToLowleft = 3,//右上到左下
};

.h

//--------------------------------------------------------------------------------
//
// Description  - 基础数据请求
// Para         - 1.(NSArray) colors,请求地址
//              - 2.(GradientType) gradientType, 渐变方向
//              - 3.(CGSize) imgSize,区域大小
//
// Return       - UIColor
// Author       - Barney
//
+ (UIColor *)gradientColorImageFromColors:(NSArray*)colors
                             gradientType:(GradientType)gradientType
                                  imgSize:(CGSize)imgSize;
//
//--------------------------------------------------------------------------------

.m

+ (UIColor *)gradientColorImageFromColors:(NSArray *)colors
                             gradientType:(GradientType)gradientType
                                  imgSize:(CGSize)imgSize {
    NSMutableArray *ar = [NSMutableArray array];
    
    for(UIColor *c in colors) {
        [ar addObject:(id)c.CGColor];
    }
    
    UIGraphicsBeginImageContextWithOptions(imgSize, YES, 1);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGColorSpaceRef colorSpace = CGColorGetColorSpace([[colors lastObject] CGColor]);
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)ar, NULL);
    CGPoint start;
    CGPoint end;
    
    switch (gradientType) {
        case GradientTypeTopToBottom:
            start = CGPointMake(0.0, 0.0);
            end = CGPointMake(0.0, imgSize.height);
            break;
        case GradientTypeLeftToRight:
            start = CGPointMake(0.0, 0.0);
            end = CGPointMake(imgSize.width, 0.0);
            break;
        case GradientTypeUpleftToLowright:
            start = CGPointMake(0.0, 0.0);
            end = CGPointMake(imgSize.width, imgSize.height);
            break;
        case GradientTypeUprightToLowleft:
            start = CGPointMake(imgSize.width, 0.0);
            end = CGPointMake(0.0, imgSize.height);
            break;
        default:
            break;
    }
    
    CGContextDrawLinearGradient(context, gradient, start, end, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    CGGradientRelease(gradient);
    CGContextRestoreGState(context);
    CGColorSpaceRelease(colorSpace);
    UIGraphicsEndImageContext();
    
    return [UIColor colorWithPatternImage:image];
}
是不是很棒棒

参考资料:


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,425评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,058评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,186评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,848评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,249评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,554评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,830评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,536评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,239评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,505评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,004评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,346评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,999评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,060评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,821评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,574评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,480评论 2 267

推荐阅读更多精彩内容