iOS屏幕适配开发实用技巧

2020-01-18 13:55:12王冬梅

一、旋转处理

第一步:注册通知


[[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(changeFrames:)                           
  name:UIDeviceOrientationDidChangeNotification
     object:nil];  

第二步:处理接收事件


-(void)changeFrames:(NSNotification *)notification{
  NSLog(@"change notification: %@", notification.userInfo);
  float width=[[UIScreen mainScreen]bounds].size.width*[[UIScreen mainScreen] scale];
  float height=[[UIScreen mainScreen]bounds].size.height*[[UIScreen mainScreen] scale];
  if ([[UIDevice currentDevice] orientation]==UIInterfaceOrientationPortrait
    || [[UIDevice currentDevice] orientation]==UIInterfaceOrientationPortraitUpsideDown) {
    NSLog(@">>>portrait");
    self.frame=CGRectMake(0, 0, height, width);
  }else{
    NSLog(@">>>landscape");
    self.frame=CGRectMake(0, 0, width, height);
  }
  
  NSLog(@"view—> %@",self);
}

二、获取屏幕分辨率


 //得到当前屏幕的尺寸:
  CGSize size_screen = [[UIScreenmainScreen]bounds].size;
  //获得缩放率:
  CGFloat scale_screen = [UIScreen mainScreen].scale;  

  此时屏幕尺寸的宽高与scale的乘积就是相应的分辨率值。
  CGRect sizeOfA4 = CGRectMake(0, 0, 595, 842);//生成PDF文件时按A4标准
  CGRect sizeOfA5 = CGRectMake(0, 0, 421, 595);//生成PDF文件时按A5标准

注意:不管scale=1还是scale=2,纸张的标准sizeOfA4和sizeOfA5的设置都不变,这是因为我们通常设置的宽高在iOS体系下都是逻辑上的point,并不是真实的像素!

只要屏幕是等比例放大缩小,[[UIScreenmainScreen]bounds].size都不变。不同scale的系统会自动放大或缩小,这就是所有的应用在320x480和640x960环境下无差别运行的原因。

三、设备标准

    iPhone/iPod Touch (320点 x 480点)
    普屏分辨率    320像素 x 480像素
    Retina分辨率 640像素 x 960像素

    iPad,iPad2/New iPad (768点 x 1024点)
    普屏        768像素 x 1024像素
    Retina屏  1536像素 x 2048像素

    换算关系 (在 iPhone3 上 1个 Point 相当于 1个pixel ; 而 iPhone4 上1个 point 就相当于4个 pixel;)
    普屏       1点 = 1像素   image.png
    Retina屏   1点 = 2像素   image@2x.png   

四、真机与模拟器判断+设备类型判断


 #if defined(TARGET_IPHONE_SIMULATOR) && TARGET_IPHONE_SIMULATOR
    NSLog(@" on simulator");
 #else
    NSLog(@"not on simulator");
#endif