【问题标题】:NSBezierPath Object Appears to Be Drawing Variable Line WidthNSBezierPath 对象似乎正在绘制可变线宽
【发布时间】:2014-02-26 03:25:24
【问题描述】:

好的,所以我正在尝试绘制一个虚线框,该虚线框被细分为我要放置内容的部分。这是我的代码:

NSBezierPath *path = [NSBezierPath bezierPathWithRect:dirtyRect];
[path setLineWidth:3];
CGFloat pattern[2] = {5, 5};
[path setLineDash:pattern count:2 phase:0];
CGFloat totalHeight = header.frame.origin.y - 10;
CGFloat sectionOffset = 0;
if([game getNumPlayers] == 2) {
    sectionOffset = totalHeight / 2;
} else if([game getNumPlayers] == 3) {
    sectionOffset = totalHeight / 3;
} else if([game getNumPlayers] == 4) {
    sectionOffset = totalHeight / 4;
}
for(int i = 0; i < [[game getPlayers] count]; i++) {
    [path moveToPoint:NSMakePoint(0, totalHeight - (sectionOffset * i))];
    [path lineToPoint:NSMakePoint(dirtyRect.size.width, totalHeight - (sectionOffset * i))];
}
[path stroke];

这包含在我的自定义视图的 drawRect 方法中,因此dirtyRect 是一个等效于视图边界的 NSRect。变量 header 引用了 superview 中的另一个视图,我将这些线的位置作为其基础。

这是这段代码实际绘制的屏幕截图(显然标签除外):

如您所见,除非我们正在处理一种非常不幸的视觉错觉,我对此表示怀疑,否则盒子中包含的分隔线似乎比盒子的轮廓更厚。我已将路径对象的 lineWidth 明确设置为 3,所以我不确定这是为什么。如果能提供任何建议,我将不胜感激。

【问题讨论】:

    标签: objective-c cocoa drawing nsbezierpath thickness


    【解决方案1】:

    好的,我认为问题在于您的外框刚刚被其视图的边缘剪裁。您要求一条 3 点宽的线,因此如果您的 dirtyRect 是视图的实际边界,那么封闭框的 1.5 点将在视图之外 ,因此您只会看到边缘线1.5个点。

    内线显示完整的 3 点粗细。

    您可以通过以下方式解决此问题:

    const CGFloat lineWidth = 3;
    NSBezierPath *const path = [NSBezierPath bezierPathWithRect:NSInsetRect(dirtyRect, lineWidth/2, lineWidth/2)];
    path.lineWidth = lineWidth;
    

    【讨论】:

    • 完美!我自己从来没有想过它,但是当你想到它时,它是完全有道理的。视图外的东西被剪掉了,从线的边缘绘制没有任何意义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    • 2012-08-21
    • 2014-05-30
    • 2022-10-25
    • 2012-06-09
    • 1970-01-01
    相关资源
    最近更新 更多