#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];
}
抱歉我的英语很差。
答案 0 :(得分:1)
您正在将形状图层添加为遮罩层。这允许掩模层的像素的亮度确定其掩蔽的层的不透明度。听起来这不是你想要的。
而是将您的形状图层添加为视图图层的子图层。改变
self.layer.mask = shapeLayer;
到
[self.layer addSublayer: shapeLayer];
这将使您的形状图层在视图的图层上绘制。