Abs3akt Abs3akt - 1 month ago 9
iOS Question

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

Answer

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];
}