【问题标题】:Adding border and Rounded Rect in the NSView在 NSView 中添加边框和圆角矩形
【发布时间】:2011-02-15 14:37:18
【问题描述】:

在我的应用程序中,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 中绘制边框,但它看起来很复杂,任何人都可以建议我任何其他方法

亲切的问候

罗汉

【问题讨论】:

    标签: cocoa macos nsview


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      我在 InitWithFrame 中有这个作为我的视图:

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

      【讨论】:

        【解决方案3】:

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

        override func viewDidLoad() {
                super.viewDidLoad()
        
                self.view.wantsLayer = true
            }
        

        【讨论】:

          猜你喜欢
          • 2011-02-03
          • 1970-01-01
          • 2016-09-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-07-11
          • 1970-01-01
          相关资源
          最近更新 更多