NSImageView圆角+笔画

Ras*_*yrk 6 macros cocoa objective-c nsimage nsimageview

我有子类NSImageView,我想用圆角绘制边框.它工作,但我也需要剪掉图像的角落.

请看我的截图:

在此输入图像描述

我创建了这个代码来绘制边框/角落.

- (void)drawRect:(NSRect)dirtyRect
{
    [super drawRect:dirtyRect];

    NSColor *strokeColor;
    if(self.isSelected)
        strokeColor = [NSColor colorFromHexRGB:@"f9eca2"];
    else
        strokeColor = [NSColor colorFromHexRGB:@"000000"];

    [strokeColor set];    
    [[NSBezierPath bezierPathWithRoundedRect:NSInsetRect(dirtyRect, 1, 1) xRadius:5 yRadius:5] stroke];
}
Run Code Online (Sandbox Code Playgroud)

我应该怎么做图像剪辑?

编辑:

我修好了,但我觉得这是一种丑陋的方式.还有什么更聪明的吗?

新代码:

- (void)drawRect:(NSRect)dirtyRect
{
    NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:NSInsetRect(dirtyRect, 2, 2) xRadius:5 yRadius:5];

    [path setLineWidth:4.0];
    [path addClip];

    [self.image drawAtPoint: NSZeroPoint
                 fromRect:dirtyRect
                 operation:NSCompositeSourceOver
                 fraction: 1.0];

    [super drawRect:dirtyRect];

    NSColor *strokeColor;
    if(self.isSelected)
    {
        strokeColor = [NSColor colorFromHexRGB:@"f9eca2"];
    }
    else
        strokeColor = [NSColor colorFromHexRGB:@"000000"];

    [strokeColor set];    
    [NSBezierPath setDefaultLineWidth:4.0];
    [[NSBezierPath bezierPathWithRoundedRect:NSInsetRect(dirtyRect, 2, 2) xRadius:5 yRadius:5] stroke];
}
Run Code Online (Sandbox Code Playgroud)

yin*_*kou 4

将 s 图层的角半径NSImageView也设置为 5 px,并将其maskToBounds属性设置为YES

  • 为什么 stackoverflow 上的每一个人都假设 Objective-C 代码 == iOS? (18认同)
  • `NSImageView` 没有 `clipsToBounds` 属性 - 它是 NS 而不是 UI ImageView。 (3认同)
  • 如果你仔细阅读答案,你会发现他正在谈论图像视图的图层,即使在 AppKit 中,该图层也有一个 ClipToBounds 属性。编辑:不要忘记使用“-[NSView setWantsLayer:YES]”启用图层 (3认同)