在 iOS 中绘制尺子 - 在屏幕上精确 1 厘米 - 如何绘制相距 1 毫米的线条?

Drawing a ruler in iOS - accurate 1 cm on screen - how to draw lines 1 mm apart?

我正在尝试为任何可用的 iOS 设备绘制一个标尺,lines/ticks 开始之间的距离精确为 1 毫米。通常我会得到 PPI 并计算我的像素距离。使用Objective-C,这样好像不行。

linesDist 应该包含我在 "screen coordinate pixels" 中的 1mm 距离。

有什么想法,我该如何实现?

我的基本代码如下所示:RulerView.m,这是一个 UIView:

-(void)drawRect:(CGRect)rect
{
    [[UIColor blackColor] setFill];

    float linesDist = 3.0; // 1mm * ppi ??

    float linesWidthShort = 15.0;
    float linesWidthLong = 20.0;

    for (NSInteger i = 0, count = 0; i <= self.bounds.size.height; i = i + linesDist, count++)
    {
        bool isLong = (int)i % 5 == 0;

        float linesWidth = isLong ? linesWidthLong : linesWidthShort;
        UIRectFill( (CGRect){0, i, linesWidth, 1} );
    }
}

编辑 ppi检测(真的很难看),基于下面的答案:

float ppi = 0;
switch ((int)[UIScreen mainScreen].bounds.size.height) {
    case 568: // iPhone 5*
    case 667: // iPhone 6
        ppi = 163.0;
        break;

    case 736: // iPhone 6+
        ppi = 154.0;
        break;

    default:
        return;
        break;
}

我不确定,但是屏幕尺寸是以像素或点为单位计算的。您可以考虑它们中的任何一个并进行数学运算以创建等于或约等于毫米的比例 1 pixel = 0.26 mm and 1 point = 0.35 mm.

所以在你的情况下,每1毫米画一个标记,将近3个点。

尝试这样的事情:

UIView *markView = [[UIView alloc] initWithFrame:CGRectMake(x, y, 1, 1)];
lineView.backgroundColor = [UIColor blackColor];
[self.view addSubview:lineView];

// and increment the (x,y) coordinate for 3 points and draw a mark

iPhones(iPhone6+ 可能除外)是每英寸 163 "logical" 点。显然 4 以后的手机具有两倍或更多的分辨率,但这对坐标系没有任何影响。

1mm 因此是 163/25.4 或大约 6.4。 iPad是每毫米5.2点,iPadmini和iPhone是一样的。

-(void)drawRect:(CGRect)rect
{
    [[UIColor blackColor] setFill];
    float i;

    float linesDist = 163.0/25.4; // ppi/mm per inch (regular size iPad would be 132.0)

    float linesWidthShort = 15.0;
    float linesWidthLong = 20.0;

    for (i = 0, count = 0; i <= self.bounds.size.height; i = i + linesDist, count++)
    {
        bool isLong = (int)count % 5 == 0;

        float linesWidth = isLong ? linesWidthLong : linesWidthShort;
        UIRectFill( (CGRect){0, i, linesWidth, 1} );
    }
} 

您想对 i 使用浮点数,以避免在添加距离时出现舍入错误并避免不必要的转换。