在NSView中添加边框和圆角矩形

11

我的应用程序中,NSView 应该具有圆角矩形和边框。我尝试了以下方法:

static CGColorRef CGColorCreateFromNSColor (CGColorSpaceRef
                                            colorSpace, NSColor *color)
{
    NSColor *deviceColor = [color colorUsingColorSpaceName:
                            NSDeviceRGBColorSpace];

    float components[4];
    [deviceColor getRed: &components[0] green: &components[1] blue:
     &components[2] alpha: &components[3]];

    return CGColorCreate (colorSpace, components);
}

并在 InitWithframe 中添加了以下代码行

    [[self layer] setCornerRadius:505];
    [[self layer] setBorderWidth:500.0];
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB ();
    CGColorRef cgColor = CGColorCreateFromNSColor (colorSpace, [NSColor whiteColor]);
    CGColorSpaceRelease (colorSpace);
    [[self layer] setBorderColor:cgColor];

但是没有任何效果,还有其他的方法吗?

我猜想另一种方法是,在drawRect中绘制边框,但这似乎非常复杂,有人能否建议我其他的方法?

顺祝商祺

Rohan

3个回答

13

谢谢你关注这个问题,我使用的这个逻辑对我有效。

- (void)drawRect:(NSRect)rect
{
   if([self hasBorder])
    [self drawBorder:rect];

}

-(void)drawBorder:(NSRect)rect{
    NSRect frameRect = [self bounds];

    if(rect.size.height < frameRect.size.height) 
        return;
    NSRect newRect = NSMakeRect(rect.origin.x+2, rect.origin.y+2, rect.size.width-3, rect.size.height-3);

    NSBezierPath *textViewSurround = [NSBezierPath bezierPathWithRoundedRect:newRect xRadius:10 yRadius:10];
    [textViewSurround setLineWidth:BORDER_WIDTH];
    [pBorderColor set];
    [textViewSurround stroke];
}

10

为了使图层属性生效,您需要首先将NSView上的setWantsLayer设置为YES。

我在视图的InitWithFrame中有以下代码:

[self setWantsLayer: YES];
[self.layer setBorderWidth: 2];
[self.layer setCornerRadius: 10];

0
对之前的答案进行了一点增强。如果您不想为NSView创建子类,而它又是控制器的基本视图,您也可以这样做:
override func viewDidLoad() {
        super.viewDidLoad()

        self.view.wantsLayer = true
    }

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