我知道几种向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/相似
那么什么是最有效和可扩展的方式来添加渐变作为背景?
正如上面提到的Fogmeister,在子类的drawRect:方法中做到这一点UIView.
- (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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7146 次 |
| 最近记录: |