就像 Nikolai Ruhe 所说,最好的选择是使用您的形状作为剪切路径,然后在形状边界框内绘制一些模式。以下是代码示例:
- (void)drawRect:(CGRect)rect
{
UIBezierPath *aPath = [UIBezierPath bezierPath];
[aPath moveToPoint:CGPointMake(100.0, 0.0)];
[aPath addLineToPoint:CGPointMake(200.0, 40.0)];
[aPath addLineToPoint:CGPointMake(160, 140)];
[aPath addLineToPoint:CGPointMake(40.0, 140)];
[aPath addLineToPoint:CGPointMake(0.0, 40.0)];
[aPath closePath];
[aPath setLineWidth:10];
CGRect bounds = aPath.bounds;
UIBezierPath *stripes = [UIBezierPath bezierPath];
for ( int x = 0; x < bounds.size.width; x += 20 )
{
[stripes moveToPoint:CGPointMake( bounds.origin.x + x, bounds.origin.y )];
[stripes addLineToPoint:CGPointMake( bounds.origin.x + x, bounds.origin.y + bounds.size.height )];
}
[stripes setLineWidth:10];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState( context );
[aPath addClip];
[[UIColor blueColor] set];
[stripes stroke];
CGContextRestoreGState( context );
[[UIColor greenColor] set];
[aPath stroke];
}
使用Swift
override func draw(_ rect: CGRect){
let aPath = UIBezierPath()
aPath.move(to: CGPoint(x: 100.0, y: 0.0))
aPath.addLine(to: CGPoint(x: 200.0, y: 40.0))
aPath.addLine(to: CGPoint(x: 160, y: 140))
aPath.addLine(to: CGPoint(x: 40.0, y: 140))
aPath.addLine(to: CGPoint(x: 0.0, y: 40.0))
aPath.close()
aPath.lineWidth = 10
let bounds = aPath.bounds
let stripes = UIBezierPath()
for x in stride(from: 0, to: bounds.size.width, by: 20){
stripes.move(to: CGPoint(x: bounds.origin.x + x, y: bounds.origin.y ))
stripes.addLine(to: CGPoint(x: bounds.origin.x + x, y: bounds.origin.y + bounds.size.height ))
}
stripes.lineWidth = 10
let context = UIGraphicsGetCurrentContext()
context!.saveGState()
aPath.addClip()
UIColor.blue.set()
stripes.stroke()
context!.restoreGState()
UIColor.green.set()
aPath.stroke()
}
产生的结果
![enter image description here](https://istack.dev59.com/zgw9t.webp)