【问题标题】:NSTextFieldCell rounded corners stroke not roundedNSTextFieldCell 圆角笔划不圆角
【发布时间】:2014-02-24 18:09:04
【问题描述】:

我想要一个带有圆角的 NSTextField,为此我将我的 NSTextFieldCell 子类化,并使用了drawInteriorWithFrame:(NSRect) inView:(NSView *) 我的代码看起来像这样:

-(void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView {

//Color Declarations
NSColor* fillColor = [NSColor colorWithCalibratedRed: 1 green: 1 blue: 1 alpha: 1];
NSColor* strokeColor = [NSColor colorWithCalibratedRed: 0.679 green: 0.679 blue: 0.679 alpha: 1];

//Shadow Declarations
NSShadow* shadow = [[NSShadow alloc] init];
[shadow setShadowColor: strokeColor];
[shadow setShadowOffset: NSMakeSize(0.1, 0.1)];
[shadow setShadowBlurRadius: 4];

//Rounded Rectangle Drawing
NSBezierPath* roundedRectanglePath = [NSBezierPath bezierPathWithRoundedRect:cellFrame xRadius: 10 yRadius: 10];
[fillColor setFill];
[roundedRectanglePath fill];

//Rounded Rectangle Inner Shadow
NSRect roundedRectangleBorderRect = NSInsetRect([roundedRectanglePath bounds], -shadow.shadowBlurRadius, -shadow.shadowBlurRadius);
roundedRectangleBorderRect = NSOffsetRect(roundedRectangleBorderRect, -shadow.shadowOffset.width, -shadow.shadowOffset.height);
roundedRectangleBorderRect = NSInsetRect(NSUnionRect(roundedRectangleBorderRect, [roundedRectanglePath bounds]), -1, -1);

NSBezierPath* roundedRectangleNegativePath = [NSBezierPath bezierPathWithRect: roundedRectangleBorderRect];
[roundedRectangleNegativePath appendBezierPath: roundedRectanglePath];
[roundedRectangleNegativePath setWindingRule: NSEvenOddWindingRule];

[NSGraphicsContext saveGraphicsState];
{
    NSShadow* shadowWithOffset = [shadow copy];
    CGFloat xOffset = shadowWithOffset.shadowOffset.width + round(roundedRectangleBorderRect.size.width);
    CGFloat yOffset = shadowWithOffset.shadowOffset.height;
    shadowWithOffset.shadowOffset = NSMakeSize(xOffset + copysign(0.1, xOffset), yOffset + copysign(0.1, yOffset));
    [shadowWithOffset set];
    [[NSColor grayColor] setFill];
    [roundedRectanglePath addClip];
    NSAffineTransform* transform = [NSAffineTransform transform];
    [transform translateXBy: -round(roundedRectangleBorderRect.size.width) yBy: 0];
    [[transform transformBezierPath: roundedRectangleNegativePath] fill];
}
[NSGraphicsContext restoreGraphicsState];

[strokeColor setStroke];
[roundedRectanglePath setLineWidth: 2];
[roundedRectanglePath stroke];

[super drawInteriorWithFrame:cellFrame inView:controlView];
}

除了没有圆角的边框外,结果看起来很棒。图片胜于文字:My NSTextField

接受所有帮助! :D 提前谢谢你。

更新 我用你说的网站代码复制粘贴了,但我仍然遇到同样的问题...... NSTextField with on rounded corner

【问题讨论】:

标签: objective-c macos cocoa


【解决方案1】:

如果您想要一个所有角都是圆角的文本字段,您可以简单地在其Attributes Inspector 中选择Text Field 中的Border。或者绘制任意一个圆角的文本字段,通过this

另外,如果你想绘制一个自定义的圆角文本字段,只需按照上面链接中的步骤操作,但不是绘制一个圆角的贝塞尔路径,而是简单地使用一个圆角绘制一个贝塞尔路径

 [NSBezierPath bezierPathWithRoundedRect:textfieldrect xRadius:10 yRadius:10]

【讨论】:

  • 其实我不想要圆角,但是圆角更直观...