如何将图像固定在屏幕中央,无论位置是否需要在任何屏幕中间固定指南针
这是我的代码
_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;
但是图像固定在左侧,我需要不依赖于屏幕中心的位置
答案 0 :(得分:1)
这是一种方法:
在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;
然后每次屏幕旋转时调用此方法:
- (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];
}
答案 1 :(得分:1)
问题很简单
我的行动:
第1步
_backgroundImageView.image = [UIImage imageNamed:@"background.jpg"];
[self.view sendSubviewToBack:self.backgroundImageView];
答案 2 :(得分:0)
使用此代码可能对您有帮助。
CanvasRenderer