NSTextFieldCell圆角描边不圆

时间:2014-02-24 18:09:05

标签: objective-c macos cocoa

我希望有一个带圆角的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

1 个答案:

答案 0 :(得分:0)

如果您想要一个四舍五入的文字字段,您可以在其Border中选择Text Field Attributes Inspector。或者要绘制任意一个圆角的文本字段,请浏览this

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

绘制所有圆角的贝塞尔曲线路径
 [NSBezierPath bezierPathWithRoundedRect:textfieldrect xRadius:10 yRadius:10]