我正在尝试创建一个Uiview子类(“渐变视图”),该子类将充满各种颜色的梯度。我已经通过将Cagradientlayer作为Uiview层的子层来实现。

看起来不错,但是当屏幕旋转时,它没有调整梯度层的大小。我没有运气在层上找到布尔属性要切换,因此我在渐变视图中覆盖了Layoutsupsubviews。

-(void)layoutSubviews {
    self.gradientLayer.frame = self.bounds;
}

这有效,但是在设备旋转动画中,渐变视图背后的东西仍然可见。什么是“自动化”该Cagradientlayer匹配其父层的边界以使动画平滑的最简单方法是什么?

有帮助吗?

解决方案

您可能可以在自定义Uiview上定义 +Layerclass方法...

@implementation MyGradientView
+(Class) layerClass {
    return [CAGradientLayer class];
}
@end

您可以在控制器的ViewDidload()(或任何地方)中初始化该图层,例如...

-(void)viewDidLoad {
    [super viewDidLoad];
    [(CAGradientLayer*)[mMyGradientViewInstance layer] setColors:nil];
}

其他提示

我会:

  1. 增加 您的视图大小 最大每个 WillrotateToInterfaceorientation代码中的维度。 (例如,对于320x480 iPhone-将DIM设置为480x480)。

  2. 根据didrotatefrominterfaceorientation函数中的新旋转视图设置界限。

这应该使视图足够大,因此无论在动画过程中如何定向,它都将覆盖整个屏幕。它不会是“平滑的” - 因为必须旋转梯度,但是至少您不会在旋转中间看到层后面。

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {

    CGRect b;

    if(UIInterfaceOrientationIsLandscape(toInterfaceOrientation))b = CGRectMake(0, 0, 480, 320);
    else b = CGRectMake(0, 0, 320, 480);    

    [CATransaction begin];
    [CATransaction setValue:[NSNumber numberWithFloat:duration] forKey:kCATransactionAnimationDuration];
    [self.view.layer setBounds:b];
    [CATransaction commit];

}

请注意,返回Cagradientlayer作为图层类仅在将视图背景颜色设置为透明时才有效。如果需要透明以外的颜色,则需要设置图层背景颜色。

就我而言,这项工作:

[[[view.layer sublayers] objectAtIndex:gradientIndex] setFrame:view.bounds];
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top