旋转时无法获得背景渐变以填满整个屏幕

我有一个背景渐变,当屏幕最初以纵向模式渲染时,它可以很好地绘制。 但是,当设备旋转到横向模式时,屏幕的右侧40%是黑色的(即,未在先前绘制的屏幕部分上绘制背景)。 我不知道如何让背景重绘以填满整个屏幕。

谁能告诉我我做错了什么? 谢谢!

以下是最初绘制时的外观。 在此处输入图像描述

现在轮到它时它看起来像是:

在此处输入图像描述

这是我的背景渐变类的代码:

#import "BackgroundGradient.h" @interface BackgroundGradient() @property (strong, nonatomic) UIView *view; @end @implementation BackgroundGradient - (id) initWithView:(UIView *) view { if (!_view) _view = view; return self; } - (void) makeGradient { UIColor *darkOp = [UIColor colorWithRed:(193.0 / 255.0) green:(215.0 / 255.0) blue:(46.0 / 255.0) alpha: 1]; UIColor *lightOp = [UIColor colorWithRed:(222.0 / 255.0) green:(233.0 / 255.0) blue:(143.0 / 255.0) alpha: 1]; // Create the gradient CAGradientLayer *gradient = [CAGradientLayer layer]; // Set colors gradient.colors = [NSArray arrayWithObjects: (id)darkOp.CGColor, (id)lightOp.CGColor, (id)darkOp.CGColor, nil]; // Update the start and end points gradient.startPoint = CGPointMake(0.5, 0.0); gradient.endPoint = CGPointMake(0.5, 1.0); // Set bounds gradient.frame = self.view.bounds; // Add the gradient to the view [self.view.layer insertSublayer:gradient atIndex:0]; gradient.locations = [NSArray arrayWithObjects: [NSNumber numberWithFloat:0.0f], [NSNumber numberWithFloat:0.7], [NSNumber numberWithFloat:0.9], nil]; } @end 

最后,这是我如何实例化背景对象:

 - (void)viewDidLoad { [super viewDidLoad]; self.background = [[BackgroundGradient alloc] initWithView:self.view]; [self.background makeGradient]; } 

编辑:我添加了以下代码,包括对起点和终点的更新(上图):

 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { [self.background makeGradient]; } 

我快到了,但现在,我明白了。 注意还有一条垂直线。 在我看来,新的背景正在被绘制在前一个背景上,以至于之前的背景仍然存在并阻挡了新的背景。 当从纵向到横向的动画正在发生时,这尤其明显。

在此处输入图像描述

这是你做错的地方: CAGradientLayer *gradient = [CAGradientLayer layer];[self.view.layer insertSublayer:gradient atIndex:0];

每次设备旋转时,您都在“添加”渐变图层的新实例。 你不应该这样做。 相反,只在旋转时设置它的框架,一切都将正常工作。 仅使用一个实例。 在viewDidLoad创建它

在这种情况下使用视图调试来帮助解决问题。

我用这个解决了这个问题:调整背景图像的子图层。

迅速

 override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { self.backgroundImageView.layer.sublayers?.first?.frame = self.view.bounds } 

viewDidLayoutSubviews更新渐变的帧:

 override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // find gradient layer let gradLayers = gradientView.layer.sublayers?.flatMap { $0 as? CAGradientLayer } // this assumes there is only one gradient layer gradLayers?.first?.frame = gradientView.bounds }