点:即point,
在编程中,frame、bounds、center等设置的坐标位置中使用的CGFloat参数就是以点(point)为单位,应用到逻辑坐标系。
像素:即pixel,
在实际屏幕中,是以像素(pixel)为基本计量单位的,应用到设备坐标系。
所以这两个坐标系需要进行转换,那么会用到转换因子
[UIScreen mainScreen].scale
scale是逻辑坐标转换为设备坐标的因数。在普通屏幕,scale1为1,表示1个点等于1像素;在视网膜屏幕上,scale为2,表示1个点等于2像素;但在6Plus设备上,scale为3,表示1个点等于3像素。
所以在根据设计好的UI来编程时,frame需要用到最基本的那个图,在@2x、@3x的frame时,需要除以2或3即可。
在UIImage与CGImageRef转换时,有时会需要用到上述
如把一个UIImage裁剪成12等分,并分别显示到按钮上
若不进行转换,直接设置
-(void)test{
UIImage *bigImg = [UIImage imageNamed:@"LuckyAstrology"];
CGFloat smallImgW = bigImg.size.width/12 ;
CGFloat smallImgH = bigImg.size.height;
for (NSInteger i=0; i<12; i++) {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect smallRect = CGRectMake(i*smallImgW, 0, smallImgW, smallImgH);
CGImageRef samllImg = CGImageCreateWithImageInRect(bigImg.CGImage, smallRect);
[btn setBackgroundImage:[UIImage imageWithCGImage:samllImg] forState:UIControlStateNormal];
btn.frame = CGRectMake(smallImgW*i, 200, smallImgW, smallImgH);
[self.view addSubview:btn];
}
}
那么效果是
正确的应是对smallImgW和smallImgH这两个属性进行转换
-(void)test{
UIImage *bigImg = [UIImage imageNamed:@"LuckyAstrology"];
CGFloat scaleNum = [UIScreen mainScreen].scale;
//在该处设置
CGFloat smallImgW = bigImg.size.width/12 * scaleNum;
CGFloat smallImgH = bigImg.size.height* scaleNum;
for (NSInteger i=0; i<12; i++) {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect smallRect = CGRectMake(i*smallImgW, 0, smallImgW, smallImgH);
CGImageRef samllImg = CGImageCreateWithImageInRect(bigImg.CGImage, smallRect);
[btn setBackgroundImage:[UIImage imageWithCGImage:samllImg] forState:UIControlStateNormal];
btn.frame = CGRectMake(smallImgW*i, 200, smallImgW, smallImgH);
[self.view addSubview:btn];
}
}
效果为