我知道几种向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];
}
- 创建UIView的子视图,但不要覆盖drawRect,而是使用CAGradientLayer . 与http://nscookbook.com/2013/04/recipe-20-using-cagradient-layer-in-a-custom-view/相似
那么什么是最有效和可扩展的方式来添加渐变作为背景?
2 回答
正如上面提到的Fogmeister,在
UIView
子类的drawRect:
方法中执行此操作 .DrawRect是我认为更有效的方式 . 我想扩展jverrijt的好答案 . 如果你需要alpha组件(对黑色渐变f.e.透明),那么你可以使用: