我创建了NSImageView的子类,并希望在其周围绘制带有圆角的边框。虽然代码能够实现该功能,但我需要将图像的角剪裁掉。
请查看我的截图: 我已经编写了以下代码来绘制边框/角落:
请查看我的截图: 我已经编写了以下代码来绘制边框/角落:
- (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];
}
我该怎么做才能裁剪图片?
编辑:
好了,我已经解决了,但我觉得这种方法很丑陋。有更聪明的方法吗?
新代码:
- (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
没有clipsToBounds
属性 - 它是NS ImageView而不是UI ImageView。 - SteveF-[NSView setWantsLayer:YES]
来启用图层。 - dvkch