2015-09-07 310 views
2

我想绘制一个尺子,对于任何可用的iOS设备,线条/蜱之间的精确距离为1mm。通常我会得到PPI并计算像素的距离。使用Objective-C,它似乎不能以这种方式工作。在iOS中绘制标尺 - 在屏幕上精确1厘米 - 如何绘制相距1毫米的线条?

linesDist应该在“屏幕坐标像素”中包含我的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; 
} 

回答

2

的iPhone(与iPhone6 +可能是个例外),每英寸163 “逻辑” 之分。显然,从4开始的手机的分辨率是双倍或更高,但这对坐标系没有任何影响。

因此1mm为163/25.4或约6.4。 iPad每毫米5.2点,iPad mini与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使用float,以避免在添加距离时避免舍入错误并避免不必要的转换。

+0

谢谢你:)还是觉得有点不确定:我需要检查3例:iPad的正常,iPhone6 +,休息和调整PPI /毫米? – BananaAcid

+0

是的,你需要为iPad和(可能)iPhone 6+的特殊情况。不幸的是,可靠地区分iPad和iPad mini并不是微不足道的。 –

+1

就逻辑点而言,iPhone 6似乎已经达到约154ppi。 –

0

我不确定,但是,屏幕尺寸是以像素或点计算的。您可以考虑使用它们中的任何一个,并根据您的数学创建一个等于或近似等于mm的刻度。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