罗盘每个点处的圆的外边缘都被裁剪(大概是由矩形框裁剪的)。如何让圆圈显示在框架内? (这是通过单击按钮创建的):
在我的 AppController.m
#import "AppController.h"
#import "MakeCircle.h"
@implementation AppController
- (IBAction)makeCircle:(id)sender {
MakeCircle* newCircle = [[MakeCircle alloc] initWithFrame:NSMakeRect(100.0, 100.0, 30.0, 30.0)];
[[[[NSApplication sharedApplication] mainWindow] contentView] addSubview:newCircle];
[newCircle release];
}
@end
在我的MakeCircle.m
- (void)drawRect:(NSRect)rect {
[self setNeedsDisplay:YES];
[[NSColor blackColor] setStroke];
// Create our circle path
NSBezierPath* circlePath = [NSBezierPath bezierPath];
[circlePath appendBezierPathWithOvalInRect: rect];
//give the line some thickness
[circlePath setLineWidth:4];
// Outline and fill the path
[circlePath stroke];
}
谢谢。
最佳答案
我想你只看到了一半的边缘,对吧?您可以计算边缘厚度的一半,然后从矩形中减去该值:
#define STROKE_COLOR ([NSColor blackColor])
#define STROKE_WIDTH (4.0)
- (void)drawRect:(NSRect)dirtyRect {
NSBezierPath *path;
NSRect rectangle;
/* Calculate rectangle */
rectangle = [self bounds];
rectangle.origin.x += STROKE_WIDTH / 2.0;
rectangle.origin.y += STROKE_WIDTH / 2.0;
rectangle.size.width -= STROKE_WIDTH / 2.0;
rectangle.size.height -= STROKE_WIDTH / 2.0;
path = [NSBezierPath path];
[path appendBezierPathWithOvalInRect:rectangle];
[path setLineWidth:STROKE_WIDTH];
[STROKE_COLOR setStroke];
[path stroke];
}
我目前没有 Mac,所以无法测试它,但我认为它应该可以解决您的问题。
也不要调用[self setNeedsDisplay:YES]
。当你想要重绘整个 NSView 时使用该方法,并且从绘图方法调用它有点递归。这就是为什么我对你的代码实际上绘制了一些东西感到惊讶。
我还有另一个提示:[[NSApplication sharedApplication] mainWindow]
实际上与 [NSApp mainWindow]
相同。 NSApp
是一个包含主应用程序的全局变量。
希望有帮助,
ief2
关于 cocoa NSView : Making circles but they are getting cropped,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4946949/