6

我有子类 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];
}

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

编辑:

好吧,我修好了,但我觉得这是一种丑陋的做法。有什么更聪明的吗?

新代码:

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

2 回答 2

4

NSImageViews 层的圆角半径也设置为 5 px 并将其maskToBounds属性设置为YES.

于 2012-03-04T12:22:51.167 回答
2

XCode 8.3 和 Swift 3.1 的更新答案

import Cocoa

class SomeViewController: NSViewController {
  @IBOutlet weak var artwork: NSImageView!

  override func viewDidLoad() {
    super.viewDidLoad()
    artwork.wantsLayer = true // Use a layer as backing store for this view
    artwork.canDrawSubviewsIntoLayer = true // Important, flatten all subviews into layer
    artwork.layer?.cornerRadius = 4.0
    artwork.layer?.masksToBounds = true // Mask layer
  }
}
于 2017-08-29T17:28:32.733 回答