iOS 宽高相等图片适配iPhone X
2019-04-07 本文已影响0人
一亩三分甜
一张宽高相等375*375的正方形图片显示在iPhone X上需要单独处理。

在其他机型上能完美适配,在iPhoneX效果中间会留白(下图绿色部分)。

self.backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, KNavgationBarHeight+kStatusBarHeight, kLScreenWidth, kLScreenHeight)];
self.backgroundView.backgroundColor = [UIColor greenColor];
[self.view addSubview:self.backgroundView];
CGFloat width = 375*[UIScreen mainScreen].bounds.size.width/375;
CGFloat height = 375*[UIScreen mainScreen].bounds.size.height/667;
self.backImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
self.backImageView.contentMode = UIViewContentModeScaleAspectFit;
[self.backImageView setImage:[UIImage imageNamed:@"limit_face_background"]];
[self.backgroundView addSubview:self.backImageView];
self.innerCircleImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
self.innerCircleImageView.contentMode = UIViewContentModeScaleAspectFit;
[self.innerCircleImageView setImage:[UIImage imageNamed:@"limit_face_innercircle"]];
[self.backgroundView addSubview:self.innerCircleImageView];
self.circleImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
self.circleImageView.contentMode = UIViewContentModeScaleAspectFit;
[self.circleImageView setImage:[UIImage imageNamed:@"limit_face_circle"]];
[self.backgroundView addSubview:self.circleImageView];
self.topAnimationView = [[UIView alloc] initWithFrame:CGRectMake(0, height, kLScreenWidth, kLScreenHeight - height)];
self.topAnimationView.backgroundColor = [UIColor cyanColor];
[self.backgroundView addSubview:self.topAnimationView];
其他机型的宽高比实质上是相等(1:1)的,只有iPhone X系列上面的机型宽高比不相等(375:1218*0.56 = 682)。图片是正方形UIViewContentModeScaleAspectFit,所以造成上面留白(682-562)/2=60,
机型 | 屏幕尺寸 | 比例 | 比例 |
---|---|---|---|
iPhone 4 | 640x960 | 2:3 | 0.67 |
iPhone 5 | 640x1136 | 9:16 | 0.56 |
iPhone 6 | 750x1334 | 9:16 | 0.56 |
iPhone 6p | 1242x2208 | 9:16 | 0.56 |
iPhone X | 1125x2436 | 9:16 | 0.46 |
iPhone XM | 1242x2688 | 9:16 | 0.46 |
iPhone XS | 828x1792 | 9:16 | 0.46 |
消除空白:用白色将上面60填充。
//表明有空隙
UIView *blankView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kLScreenWidth, (height-width)/2)];
blankView.backgroundColor = [UIColor whiteColor];
[self.backImageView addSubview:blankView];
UIView *blank0View = [[UIView alloc] initWithFrame:CGRectMake(0, width + (height-width)/2, kLScreenWidth, (height-width)/2)];
blank0View.backgroundColor = [UIColor whiteColor];
[self.backImageView addSubview:blank0View];

UIViewContentModeScaleAspectFit
Description
The option to scale the content to fit the size of the view by maintaining the aspect ratio. Any remaining area of the view’s bounds is transparent.
有效的根据屏幕大小填充视图,从屏幕边界多余的部分是透明的。