2014-09-08 1 views
0

Я пытаюсь поместить изображение в качестве фона для viewcontroller в приложении ipad. Я установил это с помощьюУстановите изображение в фоновое изображение для просмотра контроллера и поддерживайте его при повороте на ipad

UIImage *background = [UIImage imageNamed: @"[email protected]~ipad.png"]; 
      UIImageView *imageView = [[UIImageView alloc] initWithImage: background]; 
      imageView.frame = self.view.bounds; 
      [self.view addSubview: imageView]; 
      [self.view sendSubviewToBack:imageView]; 

Это прекрасно работает портретный режим, но когда я поворачиваю его в ландшафтном режиме, есть пустое пространство, где изображение не заполняет. Моя идея, основанная на других подобных сообщениях была иметь новую картину, которая вызывается при изменении вращения прибудет, и я попробовал этот

{ if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { 

     if((self.interfaceOrientation == UIDeviceOrientationLandscapeLeft) || (self.interfaceOrientation == UIDeviceOrientationLandscapeRight)){ 

      UIImage *background = [UIImage imageNamed: @"[email protected]~ipad.png"]; 
      UIImageView *imageView = [[UIImageView alloc] initWithImage: background]; 
      imageView.frame = self.view.bounds; 
      [self.view addSubview: imageView]; 
      [self.view sendSubviewToBack:imageView]; 



     } else if((self.interfaceOrientation == UIDeviceOrientationPortrait) || (self.interfaceOrientation == UIDeviceOrientationPortraitUpsideDown)){ 

      UIImage *background = [UIImage imageNamed: @"[email protected]~ipad.png"]; 
      UIImageView *imageView = [[UIImageView alloc] initWithImage: background]; 
      imageView.frame = self.view.bounds; 
      [self.view addSubview: imageView]; 
      [self.view sendSubviewToBack:imageView]; 
     }} 

который привел к тому же. Любые идеи о том, как исправить это, будут оценены!

+0

Когда вы поворачиваете изображение устройства к портрету или портрету к пейзажу – dheeru

+0

, когда вы поворачиваете устройство от пейзажа к портрету или от портрета к пейзажу? , если ((self.interfaceOrientation == UIDeviceOrientationLandscapeLeft) || (self.interfaceOrientation == UIDeviceOrientationLandscapeRight)) { } иначе, если ((self.interfaceOrientation == UIDeviceOrientationPortrait) || (self.interfaceOrientation == UIDeviceOrientationPortraitUpsideDown)) {} – dheeru

+0

Вы автозапуск в своем приложении? – rptwsthi

ответ

0

Проверьте настройки автоизображения просмотра, попробуйте просмотреть координаты представления NSLog, обратите внимание на свойство UIViewContentModeScale uiimageview. Почему бы вам просто не добавить изображение в свою раскадровку?

0

Рабочий код:

@interface SOViewController(){ 
    UIImageView *imageView; 
} 

@end 

-(void)initialOrientationHandling 
{ 
    //[self.view removeFromSuperview]; 

    if ([[UIDevice currentDevice]orientation] == UIDeviceOrientationLandscapeLeft || 
     [[UIDevice currentDevice]orientation] == UIDeviceOrientationLandscapeRight){ 

     imageView.frame = self.view.bounds; 

     [self.view addSubview: imageView]; 
     [self.view sendSubviewToBack:imageView]; 


    }else if ([[UIDevice currentDevice]orientation] == UIDeviceOrientationPortrait || 
       [[UIDevice currentDevice]orientation] == UIDeviceOrientationPortraitUpsideDown){ 

     imageView.frame = self.view.bounds; 

     [self.view addSubview: imageView]; 
     [self.view sendSubviewToBack:imageView]; 

    } 
    else if([[UIDevice currentDevice]orientation]== UIDeviceOrientationFaceUp){ 
     if(self.view.frame.size.height < 900){ 

     }else{ 

     } 
    } 
} 

-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation 
{ 

    [self initialOrientationHandling]; 
} 

Очевидно, что изображение будет искажено, если не сильно pixled. Я рекомендую использовать разные для разных поворотов.

+0

Так что, если я просто установил одну картинку, а в другом - другую? И ничто из этого в представлении не загрузило метод правильно? –

0

СВИФТ:

Сначала нужно создать два образа, один пейзаж размер вид, а другой для портрета.

Инициализировать ImageView

   var Imgview = UIImageView() 

В методе viewWillAppear, это изменить изображение, когда вид нагрузки, а также, когда поворот.

 override func viewWillAppear(animated: Bool) { 
    Imgview.frame = self.view.frame 


    Imgview.contentMode = UIViewContentMode.ScaleAspectFill 
    Imgview.clipsToBounds = true 
    view.addSubview(Imgview) 
     // get notification while rotating 

     NSNotificationCenter.defaultCenter().addObserver(self, selector: "rotate", name: UIDeviceOrientationDidChangeNotification, object: nil 
    ) 


     } 

Функция поворота для заданного изображения, она вызывается в центре уведомлений.

    func rotate() 
       { 

if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation)) 
{ 
    Imgview.frame = self.view.frame 
    Imgview.image = UIImage(named: "landscapeSizeimage.png") 

    self.view.sendSubviewToBack(Imgview) 


    } 

    if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation)) 
{ 
    Imgview.frame = self.view.frame 
    Imgview.image = UIImage(named: "PortraitSizeimage.png") 

    self.view.sendSubviewToBack(Imgview) 


    }} 

Это работало me.Hope помогает someone.And я не знаю, может быть это создать больше imageviews так вместо bringtosubview мы можем удалить ImageView по вашему желанию.