iOS 绘制1像素线条总结

先了解下scale
scale 即屏幕缩放系数,根据当前设备屏幕的大小计算的比例。

下面来看下不同几款设备对应的scale

设备 Size scale
4s {320, 480} 2.000000
5/5s {320, 568} 2.000000
6 {375, 667} 2.000000
6Plus {414, 736} 3.000000

以上数据是根据下面代码获取scale
CGFloat scale = [UIScreen mainScreen].scale;

实例代码

  • 设置高为1像素的视图
#define SINGLE_LINE_WIDTH           (1 / [UIScreen mainScreen].scale)
#define SINGLE_LINE_ADJUST_OFFSET   ((1 / [UIScreen mainScreen].scale) / 2)
lineWidth = SINGLE_LINE_WIDTH;
    CGFloat pixelAdjustOffset = SINGLE_LINE_WIDTH;
    //仅当要绘制的线宽为奇数像素时,绘制位置需要调整
if (((int)(lineWidth * [UIScreen mainScreen].scale) + 1) % 2 == 0) {
        pixelAdjustOffset = SINGLE_LINE_ADJUST_OFFSET;
    }

    UIView *line = [[UIView alloc] initWithFrame:CGRectZero];
//    xPos yPos
    line.frame = CGRectMake(0-pixelAdjustOffset, 100-pixelAdjustOffset, sys_w, lineWidth);
    line.backgroundColor = [UIColor redColor];
    [self.view addSubview:line];

参考链接:

  1. http://www.cocoachina.com/ios/20150629/12278.html
  2. https://developer.apple.com/library/ios/documentation/2DDrawing/Conceptual/DrawingPrintingiOS/GraphicsDrawingOverview/GraphicsDrawingOverview.html

你可能感兴趣的:(iOS开发杂记)