在Objective-C iPhone中绘制标尺

3

我正在尝试使用Brad Larson在这篇文章中的代码创建一个动态标尺。

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个刻度,我已经尝试过修改代码,但仍然没有成功。

请问如何解决这个问题?


你需要尺子有多宽? - John Smith
1
你在“玩耍”做了什么?只是改变CGPoint的坐标似乎很琐碎。试着理解代码中发生了什么,并使用更好的变量名重写它。 - Mundi
实际上我希望它是动态的,因为标尺将用于显示视频长度。例如,如果视频长度增加,则标尺长度也会增加,并且宽度也会变宽。 - user831679
重点关注CGContextMoveToPointCGContextAddLineToPoint。这里有绘制标尺的坐标。正如@Mundi所写,尝试阅读并理解它,它非常简单,您可以轻松完成。 - zrzka
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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接