UIView渐变添加的现代技术

3

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

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

    a. 当使用上述渐变时,用要装饰的视图的边界创建它,并将此背景渐变作为第一个子视图插入,即– insertSubview:atIndex:

    b. 在上面获取背景渐变视图后,将其呈现在图像上下文中并将其用作背景图像,即

    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/

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


1
我会在视图的drawRect中完成它。使用CGGradient。 - Fogmeister
2个回答

9
正如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);
}

我可以在上述方法之一中完成此操作,但在获取渐变视图后,将其作为子视图添加到索引0更有效,还是从渐变视图图像生成颜色并将其用作背景颜色? - atkabai
您可以让任何需要渐变背景的视图继承自UIView类,并通过重写其drawRect方法来绘制渐变。如果需要,可以对渐变颜色和位置进行参数化。 - jverrijt
1
在使用完颜色空间后,不要忘记调用 CGColorSpaceRelease(colorSpace) - Travelling Man

0

我认为DrawRect是更有效的方法。我想扩展jverrijt的好答案。如果您需要alpha组件(例如透明到黑色渐变),则可以使用以下内容:

UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0.0);
CGContextSaveGState(UIGraphicsGetCurrentContext());
CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeClear);
CGContextRestoreGState(UIGraphicsGetCurrentContext());

//Draw stuffs

UIGraphicsEndImageContext();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接