向UIView添加渐变的现代技术

我知道添加背景渐变到UIView的几种方法。 我想知道什么是最有效和可扩展的方式,为什么? 以下是我用过的技术:

  • 创建UIView的子视图并覆盖drawRect,在那里绘制当前上下文中的渐变。

    一个。 当使用上述渐变创建它与视图的边界我想装饰和插入此背景渐变作为第一– insertSubview:atIndex:视图,即– insertSubview:atIndex:

    湾 从上面获得背景渐变视图后,我将其渲染到图像上下文中,并将其用作背景图像,即

    UIGraphicsBeginImageContext(gradView.bounds.size);
    [gradView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *gradientImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIColor *background = [UIColor colorWithPatternImage:gradientImg];
    self.view.backgroundColor = background;
    
  • 创建可伸缩的PNG并使用它来装饰视图背景。 技巧与你装饰UIButton的方式非常相似。

    -(UIColor *)backgroundColor:(CGRect)frame
    {
        UIImage *bg = [UIImage imageNamed:@"background_23x36"];
        bg = [bg resizableImageWithCapInsets:UIEdgeInsetsMake(0.0, 11.0, 0.0, 11.0)];
        UIGraphicsBeginImageContextWithOptions(frame.size, YES, [[UIScreen mainScreen] scale]);
        [bg drawInRect:frame];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return [UIColor colorWithPatternImage:image];
    }
    
  • 创建UIView的子视图,但不是覆盖drawRect,而是使用CAGradientLayer。 与http://nscookbook.com/2013/04/recipe-20-using-cagradient-layer-in-a-custom-view/类似

  • 那么什么是最有效和可扩展的方式来添加渐变作为背景?


    正如Fogmeister上面所建议的,在你的UIView子类的drawRect:方法中执行它。

    - (void)drawRect:(CGRect)rect
    {
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGContextRef context = UIGraphicsGetCurrentContext();
    
        NSArray *gradientColors = [NSArray arrayWithObjects:(id) [UIColor redColor].CGColor, [UIColor yellowColor].CGColor, nil];
    
        CGFloat gradientLocations[] = {0, 0.50, 1};
        CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) gradientColors, gradientLocations);
    
        CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
        CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));
    
        CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
        CGGradientRelease(gradient);
        CGColorSpaceRelease(colorSpace);
    }
    

    DrawRect是我认为更有效的方式。 我想扩展jverrijt的很好的答案。 如果你需要alpha组件(对黑色渐变fe透明),那么你可以使用这个:

    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0.0);
    CGContextSaveGState(UIGraphicsGetCurrentContext());
    CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeClear);
    CGContextRestoreGState(UIGraphicsGetCurrentContext());
    
    //Draw stuffs
    
    UIGraphicsEndImageContext();
    
    链接地址: http://www.djcxy.com/p/68147.html

    上一篇: Modern technique of adding gradient to UIView

    下一篇: Website screenshots