3

BradLarsonのこの投稿のコードを使用して動的定規を作成しようとしています

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);

ただし、問題は、下のスクリーンショットのように、水平方向ではなく垂直方向にティックを作成していることです。

スクリーンショット

このような定規を描きたいのですが:

スクリーンショット2

また、25ティックを超えることはありません。コードを試してみましたが、まだ失敗しています。

この問題を解決するためのガイダンス。

4

1 に答える 1

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);
于 2012-08-16T14:58:35.277 に答える