【问题标题】:Drawing Line Separator with Cocoa用 Cocoa 画线分隔符
【发布时间】:2013-02-25 15:44:41
【问题描述】:

如何绘制这样的行分隔符:

请注意,有 2 条单像素线相互重叠。有什么建议吗?


编辑:

这是我需要的代码,在 NSBox 子类中:(或 NSView,并不重要):

- (void)drawRect:(NSRect)rect
{
    [[NSColor lightGrayColor] set];
    NSRectFill(NSMakeRect(0, 1, NSWidth(rect), 1));
    
    [[NSColor whiteColor] set];
    NSRectFill(NSMakeRect(0, 0, NSWidth(rect), 1));    
}

【问题讨论】:

  • “如何画两条线”的可能重复项。
  • 我创建了一个 NSView 子类项目,它只做一件事:画一条水平线:github.com/ashchan/KASeparatorLine。与原始问题中的线的区别在于它具有渐变。

标签: objective-c cocoa nsview nsbox


【解决方案1】:

通常这种分隔符使用NSBox 绘制,通常配置为NSBoxSeparator 类型。不过,这不是您要寻找的外观。我建议在 NSBox 子类中手绘它(这样你就可以得到正常的 NSBox 行为)。有关 NSBox 子类的示例,请参阅 Matt Gemmell 的 RoundedBox

你只需要两行,所以drawRect: 应该很简单。以这种方式封装它会使其非常灵活。

(当然,您也可以考虑只使用标准的NSBox 分隔符,而不是创建自定义外观。这就是它的用途。)

【讨论】:

  • 谢谢,我现在已经实现了绘图代码并将代码添加到我原来的问题中,以防其他人想要它。
【解决方案2】:

我在 iOS 上用类似的东西模仿它,假设 NSView 有类似的界面,我希望这会有所帮助:

UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(11, 99, 298, 1)];
lineView.backgroundColor = [UIColor darkGrayColor];
[panel addSubview:lineView];

UIView *lineView2 = [[UIView alloc] initWithFrame:CGRectMake(10, 100, 300, 1)];
lineView2.backgroundColor = [UIColor whiteColor];
[panel addSubview:lineView2];

自己看了一下 NSView 的界面,好像几乎可以直接移植:

NSView *lineView = [[NSView alloc] initWithFrame:CGRectMake(11, 99, 298, 1)];
lineView.backgroundColor = [NSColor colorWithCalibratedRed:0.4f green:0.4f blue:0.4f alpha:1.0f];
[panel addSubview:lineView];

NSView *lineView2 = [[NSView alloc] initWithFrame:CGRectMake(10, 100, 300, 1)];
lineView2.backgroundColor = [NSColor colorWithCalibratedRed:1.0f green:1.0f blue:1.0f alpha:1.0f];
[panel addSubview:lineView2];

【讨论】:

  • 问题是在 OS X 上使用 AppKit,而不是在 iOS 上使用 UIKit。
  • @AndrewMadsen 我没有发现:已修改 =]
  • 谢谢你,但我找到了另一种方法,我只需要 1 个对象。
  • “UIView *lineView”在尝试了很多来自其他地方的 drawRect 东西之后为我节省了很多精力。
【解决方案3】:

你也可以使用 CALayer

CALayer *lineLayer = [CALayer layer];
lineLayer.frame = (CGRectMake(0, 100, 300, 1));
[lineLayer setBackgroundColor:CGColorCreateGenericRGB(1.0, 1.0, 1.0, 1.0)];
[panel.layer addSublayer: lineLayer];

或(如果您无权访问图层)

CALayer *lineLayer = [CALayer layer];
lineLayer.frame = (CGRectMake(0, 100, 300, 1));
[lineLayer setBackgroundColor:CGColorCreateGenericRGB(1.0, 1.0, 1.0, 1.0)];
[panel setWantsLayer:YES];
[panel setLayer: lineLayer];

【讨论】:

    猜你喜欢
    • 2011-07-20
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    • 2012-07-08
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多