Iurceac Iurie
Iurceac Iurie

Reputation: 95

I need the center of the image on the center of the screen

how to fix the image on the center of the screen regardless of the positionI need to fix compass in the middle of any screen

this is my code

_backgroundImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background.jpg"]];

    [self.view addSubview:_backgroundImageView];

    CGPoint centerImageView = _backgroundImageView.center;
    centerImageView.x = self.view.center.x;
    _backgroundImageView.center = centerImageView;

But the image is fixed on the left side, I need to not depending on the position of the screen centered in

Now only the right position varies enter image description here Now only the right position varies enter image description here I need the center of the image on the center of the screen enter image description here

Upvotes: 1

Views: 84

Answers (3)

Iurceac Iurie
Iurceac Iurie

Reputation: 95

The question is very simple

My actions:

Step 1

_backgroundImageView.image = [UIImage imageNamed:@"background.jpg"];
[self.view sendSubviewToBack:self.backgroundImageView];

Step 2 enter image description here

Step 3 enter image description here

Upvotes: 1

Filipe Sá
Filipe Sá

Reputation: 382

This is one way to do it:

on viewDidLoad:

_backgroundImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background.jpg"]];
[self.view addSubview:_backgroundImageView];

CGRect bgImageFrame = _backgroundImageView.frame;
bgImageFrame.origin.x = (self.view.frame.size.width / 2.0) - (bgImageFrame.size.width / 2.0);
bgImageFrame.origin.y = (self.view.frame.size.height / 2.0) - (bgImageFrame.size.height / 2.0);
_backgroundImageView.frame = bgImageFrame;

then this method is called everytime the screen rotates:

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [coordinator animateAlongsideTransition:^(id  _Nonnull context) {

        CGRect bgImageFrame = _backgroundImageView.frame;
        bgImageFrame.origin.x = (self.view.frame.size.width / 2.0) - (bgImageFrame.size.width / 2.0);
        bgImageFrame.origin.y = (self.view.frame.size.height / 2.0) - (bgImageFrame.size.height / 2.0);
        _backgroundImageView.frame = bgImageFrame;

    } completion:nil];
}

Upvotes: 1

SGDev
SGDev

Reputation: 2252

use this code may be help u.

-(void)viewDidLoad {

  _backgroundImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background.jpg"]];
     [self.view addSubview:_backgroundImageView];
}

-(void)viewDidLayoutSubviews {

    [super viewDidLayoutSubviews];

    CGPoint centerImageView = _backgroundImageView.center;
    centerImageView.x = self.view.center.x;
    _backgroundImageView.center = centerImageView;
}

Upvotes: 0

Related Questions