简体   繁体   中英

Background Image repeats on Rotation for split second

I've set my background image to adjust when the device is rotated using the code below and it works fine (picture is stretched on landscape but thats ok) except for the fact that when it rotates, for a split second, the picture repeats itself before rescaling to fill the view.

-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
if (UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation))
{
    UIGraphicsBeginImageContext(self.view.frame.size);
    [[UIImage imageNamed:@"MainBackground.PNG"] drawInRect:self.view.bounds];
    UIImage *image=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    self.view.backgroundColor=[UIColor colorWithPatternImage:image];


}
if (UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation))
{
    UIGraphicsBeginImageContext(self.view.frame.size);
    [[UIImage imageNamed:@"MainBackground.PNG"] drawInRect:self.view.bounds];
    UIImage *image=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    self.view.backgroundColor=[UIColor colorWithPatternImage:image];

}
}

I thought maybe using "willanimaterotation.." would possibly cover this up but it is still noticeably irritating.

Being pretty new to all of this is there anyway to correct this/am i going about this totally wrong? At a guess I think i possibly need a way to scale the image before it rotates but i'm unsure how to code this or if its even possible.

At the moment the only way i can personally think to fix it is to create 2 separate image files for portrait and landscape which i dont really want to do.

UIImageView is the way to go here.

Note that your use of if conditions in willAnimateRotationToInterfaceOrientation are returning the same result each time. Furthermore, using this method is unnecessary. Instead, let AutoresizingMask manage the presentation of your views.

Example:

- (void)viewDidLoad
{
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"MainBackground.PNG"]];
    [imageView setAutoresizingMask: (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin)];
    [self.view addSubview:imageView];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM