iOS 实现背景颜色渐变的方式

1.通过CAGradientLayer 设置渐变的背景。

  /** 
     *  1.通过CAGradientLayer 设置渐变的背景。 
     */  
    CAGradientLayer *layer = [CAGradientLayer new];  
    //colors存放渐变的颜色的数组  
    layer.colors=@[(__bridge id)[UIColor greenColor].CGColor,(__bridge id)[UIColor whiteColor].CGColor];  
    /** 
     * 起点和终点表示的坐标系位置,(0,0)表示左上角,(1,1)表示右下角 
     */  
    layer.startPoint = CGPointMake(0.5, 0);  
    layer.endPoint = CGPointMake(0.5, 1);  
    layer.frame = self.bounds;  
    [self.layer addSublayer:layer];  
      

方法2.CGGradientRef

- (void)drawRect:(CGRect)rect{
    CGContextRef ctx = UIGraphicsGetCurrentContext();  
    CGColorSpaceRef colorSpace=CGColorSpaceCreateDeviceRGB();  
    /*指定渐变色 
     space:颜色空间 
     components:颜色数组,注意由于指定了RGB颜色空间,那么四个数组元素表示一个颜色(red、green、blue、alpha), 
     如果有三个颜色则这个数组有4*3个元素 
     locations:颜色所在位置(范围0~1),这个数组的个数不小于components中存放颜色的个数 
     count:渐变个数,等于locations的个数 
     */  
    CGFloat compoents[12]={  
        0,0,0,1,  
        0.8,0.1,0.5,1.0,  
        1.0,1.0,1.0,1.0  
    };  
      
    //设置渐变的位置  
    CGFloat locations[3]={0,0.3,1.0};  
    //创建梯度上下文  
    CGGradientRef gradient= CGGradientCreateWithColorComponents(colorSpace, compoents, locations, 3);  
      
    /*绘制线性渐变 
     context:图形上下文 
     gradient:渐变色 
     startPoint:起始位置 
     endPoint:终止位置 
     options:绘制方式,kCGGradientDrawsBeforeStartLocation 开始位置之前就进行绘制,到结束位置之后不再绘制, 
     kCGGradientDrawsAfterEndLocation开始位置之前不进行绘制,到结束点之后继续填充 
      
     startPoint endPoint 不同与上一种方法,指的是真正的坐标 
     */  
    CGContextDrawLinearGradient(ctx, gradient, CGPointMake(self.frame.size.width/2, 0), CGPointMake(self.frame.size.width/2,self.frame.size.height), kCGGradientDrawsAfterEndLocation);  
      
    //释放颜色空间  
    CGColorSpaceRelease(colorSpace);  
}

这里面也有用,暂时保存

//www.greatytc.com/p/3e0e25fd9b85

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,497评论 25 709
  • 1. 我有一高中同桌,目前法律研究生在读。昨晚他半夜上线,我还在帮人改稿子。 “诗远呀,又到春节,我不想再蒙着脸回...
    唐诗远阅读 3,010评论 55 65
  • 昨夜做了一个梦,梦到我们一起去沙漠的队伍又去了青海湖,穿过隧道的时候我们车变成了敞篷车,我们把头伸出去吹风,...
    大澎湃阅读 441评论 0 1