3

我想CAShapeLayer用两种交替的颜色(例如黑色和白色,想想 Preview.app 选择框)来描边 a 的路径。我不确定如何做到这一点,或者这是否可以使用 Quartz。

我已将 CAShapeLayer 设置为具有白色边框,然后将路径属性设置为黑色虚线。我希望这应该产生黑白虚线的效果。但是,似乎首先绘制了路径,在顶部描边了边框,请参见屏幕截图(毛皮属于我的猫),

CAShapeLayer 带有白色边框和黑色描边路径,路径首先绘制在 yb 边界之后。

任何人都可以提出更好的方法或让它发挥作用的方法吗?

编码,

// Stroke a white border
[shapeLayer setFrame:shapeRect];
[shapeLayer setBorderColor:[[NSColor whiteColor] CGColor]];
[shapeLayer setBorderWidth:1.0];

// Stroked a black dash path (along the border)
// and fill shape with clear colour
[shapeLayer setFillColor:[[NSColor clearColor] CGColor]];
[shapeLayer setStrokeColor:[[NSColor blackColor] CGColor]];
[shapeLayer setLineWidth:1.0];
[shapeLayer setLineJoin:kCALineJoinRound];
[shapeLayer setLineDashPattern:
 [NSArray arrayWithObjects:[NSNumber numberWithInt:5],
  [NSNumber numberWithInt:5],
  nil]];

CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, shapeLayer.bounds);
[shapeLayer setPath:path];
CGPathRelease(path);
4

2 回答 2

2

我认为这种方法有两个问题(混合图层边框和形状描边)

  1. 边界在(边界的)内侧,但笔划是从(路径的)中心开始的。
  2. 绘制路径后绘制边框

您可以通过插入 strokeWidth 的一半路径来对 #1 做一些事情

CGFloat halfWidth = 1.0/2.0;
CGPathAddRect(path, NULL, CGRectInset(shapeLayer.bounds, halfWidth, halfWidth));

但是边框仍将绘制在形状上方(至少我不知道如何更改顺序)。

我认为最简单的解决方案是必须在同一个容器层中塑造层。容器将用于更改框架,两个图层将用于绘图。

底层将有一个白色的笔划(没有破折号图案),而顶层将有一个黑色的虚线笔划。由于两种形状都具有相同的路径,因此它看起来像黑白虚线图案。

这样做也适用于任何形状。

于 2013-08-25T09:39:38.210 回答
0

您是否尝试使用 lineDashPhase 属性?使用它,您可以先用黑色显示虚线,然后在同一路径上显示 - 改变颜色和 lineDashPhase - 用白色显示。

于 2013-08-25T09:18:14.343 回答