我使用下面的代码画一条虚线
// get the current CGContextRef for the view
CGContextRef currentContext =
(CGContextRef)[[NSGraphicsContext currentContext]
graphicsPort];
// grab some useful view size numbers
NSRect bounds = [self bounds];
float width = NSWidth( bounds );
float height = NSHeight( bounds );
float originX = NSMinX( bounds );
float originY = NSMinY( bounds );
float maxX = NSMaxX( bounds );
float maxY = NSMaxY( bounds );
float middleX = NSMidX( bounds );
float middleY = NSMidY( bounds );
CGContextSetLineWidth( currentContext, 10.0 );
float dashPhase = 0.0;
float dashLengths[] = { 20, 30, 40, 30, 20, 10 };
CGContextSetLineDash( currentContext,
dashPhase, dashLengths,
sizeof( dashLengths ) / sizeof( float ) );
CGContextMoveToPoint( currentContext,
originX + 10, middleY );
CGContextAddLineToPoint( currentContext,
maxX - 10, middleY );
CGContextStrokePath( currentContext );
它是静态的。
但我更喜欢使破折号和间隙可移动
从右向左移动并圈出
有可能吗?
更多改进案例:
破折号和间隙自动顺时针移动
欢迎任何评论
答案 0 :(得分:2)
最简单的方法是将phase
变量设为ivar并覆盖keyDown:
- (BOOL)acceptsFirstResponder
{
return YES;
}
- (void)keyDown:(NSEvent *)theEvent
{
switch ([theEvent keyCode])
{
case 0x7B: //left cursor key
dashPhase += 10.0;
break;
case 0x7C: //right cursor key
dashPhase -= 10.0;
break;
default:
[super keyDown:theEvent];
break;
}
[self setNeedsDisplay:YES];
}
还要确保将窗口的initialResponder设置为自定义视图(我假设您在NSView子类中进行绘制)。
包装代码不应该太难。只需划分dashLengths
阵列,然后按照您想要的方式重新组装。 (您没有指定是否要拆分单个破折号)
<强>更新强>
行。我误解了你的问题中的“从右到左移动”的一部分。我以为你想要用虚线包围。如果你想绘制一个带有可移动的虚线边框的矩形,甚至更容易。把它放在一个NSView子类中,当你按←或→时,它应该绘制一个虚线矩形移动它的破折号:
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
patternRectangle = [self bounds];
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect
{
CGContextRef currentContext = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
CGContextSetLineWidth( currentContext, 10.0 );
CGFloat dashLengths[] = { 20, 30, 40, 30, 20, 10 };
CGContextSetLineDash( currentContext, dashPhase, dashLengths, sizeof( dashLengths ) / sizeof( float ) );
CGPathCreateWithRect(CGRectMake(2.0, 2.0, 100.0, 100.0), NULL);
CGContextStrokeRect(currentContext, CGRectInset(NSRectToCGRect([self bounds]), 10.0, 10.0));
CGContextStrokePath( currentContext );
}
- (BOOL)acceptsFirstResponder
{
return YES;
}
- (void)keyDown:(NSEvent *)theEvent
{
switch ([theEvent keyCode])
{
case 0x7B:
dashPhase += 10.0;
break;
case 0x7C:
dashPhase -= 10.0;
break;
default:
[super keyDown:theEvent];
break;
}
[self setNeedsDisplay:YES];
}