代码之家  ›  专栏  ›  技术社区  ›  MissYasiky

CAShapeLayer的strokeColor不工作

  •  1
  • MissYasiky  · 技术社区  · 9 年前
    #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];
    }
    

    对不起,我的英语不好。

    1 回复  |  直到 9 年前
        1
  •  1
  •   Duncan C    9 年前

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

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

    self.layer.mask = shapeLayer;
    

    [self.layer addSublayer: shapeLayer];
    

    这将导致形状层绘制在视图层的顶部。