[英]NSImageView rounded corners + stroke
I have subclasses NSImageView and i want to draw a border around with rounded corners. 我有子类NSImageView,我想用圆角绘制边框。 It works but i need to clip off the image corners as well.
它工作,但我也需要剪掉图像的角落。
Please see my screenshot: 请看我的截图:
I have created this code to draw the border/corners. 我创建了这个代码来绘制边框/角落。
- (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];
}
What should i do to make the image clip ? 我应该怎么做图像剪辑?
EDIT: 编辑:
Well i fixed it, but i feel its an ugly way to do it. 我修好了,但我觉得这是一种丑陋的方式。 Anything smarter?
还有什么更聪明的吗?
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];
}
将NSImageView
图层的角半径也设置为5像素,并将其maskToBounds
属性设置为YES
。
updated answer for XCode 8.3 and Swift 3.1 更新了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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.