views:

162

answers:

3

I'm trying to create a UIView subclass ("GradientView") that will fill itself with a gradient of various colors. I've implemented it by adding a CAGradientLayer as a sub-layer of UIView's layer.

It looked good, but when the screen was rotated, it didn't resize the gradient layer. Having no luck finding a BOOL property on the layer to toggle, I overrode layoutSubviews in the GradientView.

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

This works, but the stuff behind the GradientView is still visible during the device rotation animation. What is the easiest way to 'autoresize' that CAGradientLayer to match its parent layer's bounds so that the animation is smooth (like for UIView autoresizing)?

+1  A: 

I would:

  1. Increase the size of your view to the maximum of each dimension in the willRotateToInterfaceOrientation code. (For example for an 320x480 iPhone - set the dims to 480x480).

  2. Set the bounds in accordance to the newly-rotated view in the didRotateFromInterfaceOrientation function.

This should make it so that the view is large enough so that regardless of how it is oriented during animation, it will cover the entire screen. It won't be "smooth" - because the gradient will have to be rotated, but at least you will not see behind the layer in the middle of the rotation.

Brad
this is a fudge at best
Luke Mcneice
Okay - got a better idea? I use this tequnique in mapping programs, where I have to rotate from a 320x480 to a 480x320 and want it to appear seamless.
Brad
Please see criteria for downvoting: http://stackoverflow.com/privileges/vote-down
Brad
lesson learned, brad can you edit you answer,(even if its just capitalising a word) and i will take the dv off. (vote is locked unless edit)
Luke Mcneice
Ok - done thanx!
Brad
A: 
- (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];

}
Luke Mcneice