CAShapeLayer 的 strokeColor 不起作用

the strokeColor of CAShapeLayer not work

#import <UIKit/UIKit.h>

@interface UIView (Shape)

- (void)setShape:(CGPathRef)shape;

@end

#import "UIView+Shape.h"

@implementation UIView (Shape)
- (void)setShape:(CGPathRef)shape
{
    if (shape == nil) {
        self.layer.mask = nil;
    }

    CAShapeLayer* shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = shape;
    shapeLayer.fillColor = [[UIColor whiteColor] CGColor];
    shapeLayer.strokeColor = [[UIColor redColor] CGColor];
    shapeLayer.lineWidth = 0.5;
    self.layer.mask = shapeLayer;

}
@end

这是我的代码。我想将形状的边框颜色设置为红色,但边框总是清晰的颜色。我不得不添加一个子层,如下面的代码所示。并且有效,为什么?

 - (void)setShape:(CGPathRef)shape strokeColor:(UIColor *)color
 {
    if (shape == nil) {
        self.layer.mask = nil;
    }

    CAShapeLayer* shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = shape;
//    shapeLayer.fillColor = [[UIColor whiteColor] CGColor];
//    shapeLayer.strokeColor = [[UIColor redColor] CGColor];
//    shapeLayer.lineWidth = 0.5;
    self.layer.mask = shapeLayer;

    CAShapeLayer *borderLayer = [CAShapeLayer layer];
    borderLayer.path = shape;
    borderLayer.lineWidth = 2;
    borderLayer.fillColor = [[UIColor clearColor] CGColor];
    borderLayer.strokeColor = [color CGColor];
    [self.layer addSublayer:borderLayer];
}

抱歉我的英语不好。

您正在将形状图层添加为遮罩层。这允许遮罩层像素的亮度决定其遮罩层的不透明度。听起来这不是你想要的。

相反,将形状图层添加为视图图层的子图层。更改

self.layer.mask = shapeLayer;

[self.layer addSublayer: shapeLayer];

这将使您的形状图层绘制在视图图层的顶部。