How to draw a colored border around NSImage?

扶醉桌前 提交于 2019-12-06 01:04:06

问题


I did some research but all the answers I got were for iOS, how can I draw a colored border around NSImage in OSX app? I tried using imageView property of NSImage to set it's border width and color, but it doesn't seem to be working...

Any kind of help is highly appreciated!


回答1:


Try like this without creating subclass also it is possible. Also you can set the width ans radius accordingly:-

[imgView setWantsLayer:YES];
imgView.layer.borderWidth = 1.0;
imgView.layer.cornerRadius = 8.0;
imgView.layer.masksToBounds = YES;
CGColorRef color = CGColorRetain([NSColor colorWithCalibratedRed:0 green:100 blue:0 alpha:0.5f].CGColor);
[imgView.layer setBorderColor:color];



回答2:


You could subclass NSView and do something like this:

- (void)drawRect:(NSRect)dirtyRect
{
    [[NSColor orangeColor] set];

    NSBezierPath *path = [NSBezierPath bezierPath];
    [path appendBezierPathWithRoundedRect:outerFrame xRadius:5 yRadius:5];
    [path setLineWidth:4.0];
    [path stroke];
}

and of course change the radius values depending if you want rounded corners or not.




回答3:


In Swift 3:

imagePreview.layer!.borderWidth = 10.0
imagePreview.layer!.cornerRadius = 8.0
imagePreview.layer!.masksToBounds = true
let color: CGColor = NSColor.blue.cgColor
imagePreview.layer!.borderColor = color



回答4:


In swift:

override func draw(_ dirtyRect: NSRect) {
    // Draw Border
    borderColor.set()
    let borderPath = NSBezierPath(rect: dirtyRect)
    borderPath.lineWidth = 2.0
    borderPath.stroke()
}


来源:https://stackoverflow.com/questions/19645303/how-to-draw-a-colored-border-around-nsimage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!