objective-c - NSImageView圆角+描边

标签 objective-c cocoa macros nsimage nsimageview

我有子类 NSImageView,我想用圆角画一个边框。它可以工作,但我还需要剪掉图像的角。

请看我的截图:

enter image description here

我创建了这段代码来绘制边框/角。

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

我应该怎么做才能制作图像剪辑?

编辑:

好吧,我修复了它,但我觉得这样做很丑陋。有什么更聪明的吗?

新代码:

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

最佳答案

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

关于objective-c - NSImageView圆角+描边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9554298/

相关文章:

ios - AFNetworking 使用 PUT 请求上传图片?

objective-c - 在现代 Objective-C 中覆盖 setter 和 getter 时访问生成的 ivar 时出错

python - gdb API 预处理器宏

macros - OCaml 中的记录字段更新可以推广吗?

objective-c - 如何从我的 appDelegate 访问我的 viewController? ( swift )

ios - 如何将表格 View 单元格中的字体颜色更改为变量 UIColor?

iphone - iOS图像比较

objective-c - 如何删除 NSTextView 中段落开头的字符?

objective-c - NSN 秒数 自 时、分、秒

macros - Scala 宏和 Eclipse