在NSView中添加border和Rounded Rect

Ami*_*k12 11 macos cocoa nsview

在我的应用程序中,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);
}
Run Code Online (Sandbox Code Playgroud)

并在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];
Run Code Online (Sandbox Code Playgroud)

但没有任何影响,还有其他任何方法,

我可以猜到的另一种方法是,在drawRect绘制边框,但它似乎非常复杂,任何人都可以建议我任何其他方法

亲切的问候

罗汉

Ami*_*k12 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];
}
Run Code Online (Sandbox Code Playgroud)


Ric*_*ide 10

要使图层属性产生任何影响,您需要先将NSView上的setWantsLayer设置为YES.

我在InitWithFrame中有我的视图:

[self setWantsLayer: YES];
[self.layer setBorderWidth: 2];
[self.layer setCornerRadius: 10];
Run Code Online (Sandbox Code Playgroud)