2012-03-04 51 views
6

Tôi có lớp con NSImageView và tôi muốn vẽ đường viền xung quanh với các góc tròn. Nó hoạt động nhưng tôi cần phải cắt ra các góc hình ảnh là tốt.NSImageView góc tròn + nét ngang

Xin xem ảnh chụp màn hình của tôi:

enter image description here

Tôi đã tạo ra mã này để vẽ biên giới/góc.

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

Tôi nên làm gì để tạo hình ảnh?

EDIT:

Tôi đã sửa nó, nhưng tôi cảm thấy một cách xấu xí để làm điều đó. Bất cứ điều gì thông minh hơn?

MÃ MỚI:

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

Trả lời

3

Đặt bán kính góc của lớp NSImageView của bạn cũng đến 5 px và thiết lập thuộc tính maskToBounds của nó để YES.

+3

'NSImageView' không có một' tài sản clipsToBounds' - Đây là một NS không phải là một ImageView UI. – SteveF

+15

Tại sao mọi người thứ hai trên stackoverflow lại giả sử mã mục tiêu = c iOS? – strange

+2

nếu bạn đọc cẩn thận câu trả lời bạn sẽ thấy anh ấy đang nói về lớp của chế độ xem hình ảnh, trong đó có thuộc tính clipToBounds ngay cả trong AppKit. EDIT: đừng quên kích hoạt lớp bằng cách sử dụng '- [NSView setWantsLayer: YES]' – dvkch

0

cập nhật câu trả lời cho XCode 8.3 và 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 
    } 
}