2012-03-04 16 views
6

Ho sottoclassi NSImageView e voglio disegnare un bordo con angoli arrotondati. Funziona ma ho bisogno di tagliare anche gli angoli dell'immagine.NSImageView angoli arrotondati + corsa

Si prega di vedere il mio screenshot:

enter image description here

ho creato questo codice per disegnare il bordo/angoli.

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

cosa devo fare per rendere la clip immagine?

EDIT:

Beh ho riparato, ma sento il suo un modo brutto per farlo. Qualcosa di più intelligente?

NUOVO CODICE:

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

risposta

3

impostare il raggio angolo del vostro NSImageView s livello anche a 5 px e impostare la proprietà maskToBounds-YES.

+3

'NSImageView' non ha una proprietà' clipsToBounds' - E 'un non NS un ImageView UI. – SteveF

+15

Perché ogni seconda persona su StackOverflow assume codice obiettivo-c == iOS? – strange

+2

se leggi attentamente la risposta vedrai che sta parlando del livello della vista dell'immagine, che ha una proprietà clipToBounds anche in AppKit. EDIT: non dimenticare di abilitare il layer usando '- [NSView setWantsLayer: YES]' – dvkch

0

risposta aggiornato per XCode 8.3 e 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 
    } 
}