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. */

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

iOS 用代码绘制三级渐变背景色 CAGradientLayer / CGContextDrawLinearGradient_第1张图片
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 的方式,在渲染中对于性能的消耗还需要自行考虑。

iOS 用代码绘制三级渐变背景色 CAGradientLayer / CGContextDrawLinearGradient_第2张图片
仿佛有种发廊的感觉,很魔性

# 利用 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];
}
iOS 用代码绘制三级渐变背景色 CAGradientLayer / CGContextDrawLinearGradient_第3张图片
是不是很棒棒

参考资料:

  • iOS代码设置渐变背景色 - CaryaLiu’s Blog
  • ios实现颜色渐变的几种方法
  • resizableImageWithCapInsets:方法的探析 -
  • UIGraphicsBeginImageContext和UIGraphicsBeginImageContextWithOptions
  • iOS中的绘图教程品读后的顿悟篇(二) -
  • iOS绘图教程

iOS 用代码绘制三级渐变背景色 CAGradientLayer / CGContextDrawLinearGradient_第4张图片

你可能感兴趣的:(iOS 用代码绘制三级渐变背景色 CAGradientLayer / CGContextDrawLinearGradient)