我知道有几种方法可以为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/
那么,添加渐变背景的最有效和可扩展的方式是什么?