我知道向 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/ 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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)