2012-08-16 11 views
2

我試圖從布拉德this post創建使用代碼中的動態統治者拉爾森繪製目標C iPhone尺子

NSInteger majorTickInterval = 5; 
    NSInteger totalTravelRangeInMicrons = 1000; 
    NSInteger minorTickSpacingInMicrons = 50; 
    CGFloat currentHeight = 100; 
    int leftEdgeForTicks = 10; 
    int majorTickLength = 15; 
    int minorTickLength = 10; 

    NSInteger minorTickCounter = majorTickInterval; 
    NSInteger totalNumberOfTicks = totalTravelRangeInMicrons/minorTickSpacingInMicrons; 
    CGFloat minorTickSpacingInPixels = currentHeight/(CGFloat)totalNumberOfTicks; 

    CGContextSetStrokeColorWithColor(context, [[UIColor blackColor] CGColor]); 

    for (NSInteger currentTickNumber = 0; currentTickNumber < totalNumberOfTicks; currentTickNumber++) 
    { 
     CGContextMoveToPoint(context, leftEdgeForTicks + 0.5, round(currentTickNumber * minorTickSpacingInPixels) + 0.5); 

     minorTickCounter++; 
     if (minorTickCounter >= majorTickInterval) 
     { 
      CGContextAddLineToPoint(context, round(leftEdgeForTicks + majorTickLength) + 7**.5, round(currentTickNumber * minorTickSpacingInPixels) + 0.5); 
      minorTickCounter = 0;    
     } 
     else 
     { 
      CGContextAddLineToPoint(context, round(leftEdgeForTicks + minorTickLength) + 0.5, round(currentTickNumber * minorTickSpacingInPixels) + 0.5); 
     } 

    } 

    CGContextStrokePath(context); 

但問題是,它是在下面的截圖創建蜱垂直不是水平:

screen shot

雖然我要畫這樣的尺子:

screenshot2

而且它不給我超過25個蜱,我已經打了的代碼,但仍然不成功。

任何指導我怎樣才能解決這個問題。

+0

你需要多大的寬度? – 2012-08-16 11:54:02

+1

你做了什麼「玩耍」?改變'CGPoint'的座標似乎很微不足道。試着瞭解代碼中發生了什麼,並用更好的變量名稱重寫它。 – Mundi 2012-08-16 11:57:22

+0

其實我希望它是動態的,因爲統治者是被用來顯示視頻的長度。就像如果視頻長度增加,則標尺長度將增加太多,這將是更廣泛的 – AppDeveloper 2012-08-16 11:57:58

回答

2

這是一個實現,從我的頭頂開始......我認爲保持它的重要性易讀

CGFloat leftMargin= 10; 
CGFloat topMargin = 10; 
CGFloat height = 30; 
CGFloat width = 200; 
CGFloat minorTickSpace = 10; 
int multiple = 5;    // number of minor ticks per major tick 
CGFloat majorTickLength = 20; // must be smaller or equal height, 
CGFloat minorTickLength = 10; // must be smaller than majorTickLength 

CGFloat baseY = topMargin + height; 
CGFloat minorY = baseY - minorTickLength; 
CGFloat majorY = baseY - majorTickLength; 
CGFloat majorTickSpace = minorTickSpace * multiple; 

int step = 0; 
for (CGFloat x = leftMargin; x <= leftMargin + width, x += minorTickLength) { 
    CGContextMoveToPoint(context, x, baseY); 
    CGFloat endY = (step*multiple*minorTickLength == x) ? majorY : minorY; 
    CGContextAddLineToPoint(context, x, endY); 
    step++; // step contains the minorTickCount in case you want to draw labels 
} 
CGContextStrokePath(context);