美文网首页
IOS 绘制背景色渐变的矩形

IOS 绘制背景色渐变的矩形

作者: 代码干货 | 来源:发表于2016-03-24 11:11 被阅读300次

    <pre>

    • (void)drawRect:(CGRect)rect {
    CGFloat y = 0;
    CGContextRef context = UIGraphicsGetCurrentContext(); //高需要变
    [self _drawGradientColor:context
                        rect:CGRectMake(0, y, self.frame.size.width, incrementHeight)
                     options:kCGGradientDrawsAfterEndLocation
                      colors:self.colorsArray];
    CGContextStrokePath(context);// 描线,即绘制形状
    CGContextFillPath(context);// 填充形状内的颜色
    

    }

    /**
    02

    • 绘制背景色渐变的矩形,p_colors渐变颜色设置,集合中存储UIColor对象(创建Color时一定用三原色来创建)
      03
      **/
    • (void)_drawGradientColor:(CGContextRef)p_context

                      rect:(CGRect)p_clipRect
      
                   options:(CGGradientDrawingOptions)p_options
      
                    colors:(NSArray *)p_colors {
      

      CGContextSaveGState(p_context);// 保持住现在的context

      CGContextClipToRect(p_context, p_clipRect);// 截取对应的context

      NSUInteger colorCount = p_colors.count;

      int numOfComponents = 4;

      CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();

      CGFloat colorComponents[colorCount * numOfComponents];

      for (int i = 0; i < colorCount; i++) {

        UIColor *color = p_colors[i];
        
        CGColorRef temcolorRef = color.CGColor;
        
        const CGFloat *components = CGColorGetComponents(temcolorRef);
        
        for (int j = 0; j < numOfComponents; ++j) {
            
            colorComponents[i * numOfComponents + j] = components[j];
            
        }
      

      }

      CGGradientRef gradient = CGGradientCreateWithColorComponents(rgb, colorComponents, NULL, colorCount);

      CGColorSpaceRelease(rgb);

      CGPoint startPoint = p_clipRect.origin;

      CGPoint endPoint = CGPointMake(CGRectGetMinX(p_clipRect), CGRectGetMaxY(p_clipRect));

      CGContextDrawLinearGradient(p_context, gradient, startPoint, endPoint, p_options);

      CGGradientRelease(gradient);

      CGContextRestoreGState(p_context);// 恢复到之前的context

    }
    </pre>

    IOS 绘制背景色渐变的矩形

    相关文章

      网友评论

          本文标题:IOS 绘制背景色渐变的矩形

          本文链接:https://www.haomeiwen.com/subject/fddrlttx.html