2012-03-04 75 views
6

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

我该如何做图像剪辑?

编辑:

嗯,我固定的,但我觉得它的丑陋的方式来做到这一点。什么更聪明?

NEW CODE:

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

回答

3

设置你的NSImageView S层间的圆角半径也5 PX及其maskToBounds属性设置为YES

+3

更新的答案'NSImageView'没有一个'clipsToBounds'财产 - 这是一个NS不是一个UI ImageView的。 – SteveF 2012-09-26 10:36:16

+15

为什么每一个在stackoverflow上的人都假定objective-c代码== iOS? – strange 2013-08-30 00:21:16

+2

如果您仔细阅读答案,您会看到他正在讨论图像视图的图层,即使在AppKit中也有clipToBounds属性。编辑:不要忘记使用' - [NSView setWantsLayer:YES]启用图层' – dvkch 2015-01-07 02:48:28

0

为8.3的XCode和雨燕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 
    } 
}