将自动调整大小蒙版设置为渐变背景

时间:2014-02-27 17:30:04

标签: ios objective-c calayer autoresizingmask

我在我的应用程序的主屏幕上有一个背景,它想要在旋转时扩展以填充屏幕,虽然我试图给它自动调整屏幕虽然它不会让它因为它是CALayer。在您调整屏幕大小时,左侧有一个大的空白区域,渐变位置

以下是我用来初始化渐变的代码:

UIColor *highColor = [UIColor colorWithRed:0.0f/255.0f green:128.0f/255.0f blue:214.0f/255.0f alpha:1.000];
UIColor *lowColor = [UIColor colorWithRed:5.0f/255.0f green:69.0f/255.0f blue:150.0f/255.0f alpha:1.000];
gradientBackground = [CAGradientLayer layer];
[gradientBackground setFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
[gradientBackground setColors:[NSArray arrayWithObjects:(id)[highColor CGColor], (id)[lowColor CGColor], nil]];
backgroundLayer = [CALayer layer];
[backgroundLayer setFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
[backgroundLayer setMasksToBounds:YES];
[backgroundLayer addSublayer:gradientBackground];
backgroundObject = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
[self.view addSubview:backgroundObject];
[[backgroundObject layer] insertSublayer:backgroundLayer atIndex:0];
[backgroundObject setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];

非常感谢有关如何解决此问题的任何建议

2 个答案:

答案 0 :(得分:1)

我设法找到了一种使用CALayer的方法,只需将视图的背景设置为这样的渐变图像:

UIGraphicsBeginImageContext(self.view.frame.size);
[[UIImage imageNamed:@"home-gradient.png"] drawInRect:self.view.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.view.backgroundColor = [UIColor colorWithPatternImage:image];

答案 1 :(得分:0)

您可以在视图中嵌入图层,然后在视图上设置调整大小蒙版吗?你可以继承UIView和CALayer,然后实现视图的+layerClass方法来返回你的图层子类,并使用图层子类来绘制渐变。