首页 文章

向UIView添加渐变的现代技术

提问于
浏览
3

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

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

一个 . 使用上面的渐变时,用我想要装饰的视图边界创建它,并将此背景渐变作为第一个子视图插入,即 – 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];
}

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

2 回答

  • 0

    正如上面提到的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);
    }
    
  • 9

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

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

相关问题