您可以通过将透明颜色绘制到非透明图层来实现此目的。这可以通过使用另一种混合模式进行绘制来完成。不幸的是CAShapeLayer 不支持这个。因此,您必须编写自己的形状图层类:
@interface ShapeLayer : CALayer
@property(nonatomic) CGPathRef path;
@property(nonatomic) CGColorRef fillColor;
@property(nonatomic) CGColorRef strokeColor;
@property(nonatomic) CGFloat lineWidth;
@end
@implementation ShapeLayer
@dynamic path;
@dynamic fillColor;
@dynamic strokeColor;
@dynamic lineWidth;
- (void)drawInContext:(CGContextRef)inContext {
CGContextSetGrayFillColor(inContext, 0.0, 1.0);
CGContextFillRect(inContext, self.bounds);
CGContextSetBlendMode(inContext, kCGBlendModeSourceIn);
if(self.strokeColor) {
CGContextSetStrokeColorWithColor(inContext, self.strokeColor);
}
if(self.fillColor) {
CGContextSetFillColorWithColor(inContext, self.fillColor);
}
CGContextSetLineWidth(inContext, self.lineWidth);
CGContextAddPath(inContext, self.path);
CGContextDrawPath(inContext, kCGPathFillStroke);
}
@end
创建具有透明路径的层:
ShapeLayer *theLayer = [ShapeLayer layer];
theLayer.path = ...;
theLayer.strokeColor = [UIColor clearColor].CGColor;
theLayer.fillColor = [UIColor colorWithWhite:0.8 alpha:0.5];
theLayer.lineWith = 3.0;
theLayer.opaque = NO; // Important, otherwise you will get a black rectangle
我已经使用此代码在绿色背景前绘制了一个带有透明边框的半透明圆圈:
编辑:下面是 Swift 中图层对应的代码:
public class ShapeLayer: CALayer {
@NSManaged var path : CGPath?
@NSManaged var fillColor : CGColor?
@NSManaged var strokeColor : CGColor?
@NSManaged var lineWidth : CGFloat
override class func defaultValue(forKey inKey: String) -> Any? {
return inKey == "lineWidth" ? 1.0 : super.defaultValue(forKey: inKey)
}
override class func needsDisplay(forKey inKey: String) -> Bool {
return inKey == "path" || inKey == "fillColor" || inKey == "strokeColor" || inKey == "lineWidth" || super.needsDisplay(forKey: inKey)
}
override public func draw(in inContext: CGContext) {
if let thePath = path {
inContext.setFillColor(gray: 0.0, alpha: 1.0)
inContext.fill(self.bounds)
inContext.setBlendMode(.sourceIn)
if let strokeColor = self.strokeColor {
inContext.setStrokeColor(strokeColor)
}
if let fillColor = self.fillColor {
inContext.setFillColor(fillColor)
}
inContext.setLineWidth(self.lineWidth)
inContext.addPath(thePath)
inContext.drawPath(using: .fillStroke)
}
}
}
注意:通过使用@NSManaged 标记属性,您可以通过分别在Swift 中实现needsDisplay(forKey inKey:) 或在Objective C 中实现needsDisplayForKey: 来轻松地使属性可动画化。我已经相应地调整了 Swift 代码。
但即使你不需要动画,最好用@NSManaged 标记属性,因为QuartzCore 会复制图层,并且应该也用它复制所有属性。 Swift 中的@NSManaged 对应于Objective C 中的@dynamic,因为它避免了创建属性实现。而CALayer 分别使用value(forKey:) 和setValue(_:forKey:) 获取和设置属性值。