繁体   English   中英

在NSView中添加border和Rounded Rect

[英]Adding border and Rounded Rect in the 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);
}

并在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绘制边框,但它似乎非常复杂,任何人都可以建议我任何其他方法

亲切的问候

罗汉

谢谢你看这个,这个逻辑对我有用,

- (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];
}

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

我在InitWithFrame中有我的视图:

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

对前一个答案略有改进。 如果您不想将NSView子类化,如果它是控制器的基本视图,您也可以执行以下操作:

override func viewDidLoad() {
        super.viewDidLoad()

        self.view.wantsLayer = true
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM