我通过覆盖drawInContext:(CGContextRef)ctx
方法绘制了一个波浪层,因为该波浪线是正弦波,所以我通过计算波浪值将其切成段并将它们合并为CGMutablePathRef
这是我在-(void)drawInContext:(CGContextRef)ctx
中所做的
//join style
CGContextSetLineJoin(ctx, kCGLineJoinRound);
CGContextSetLineCap(ctx, kCGLineCapRound);
CGContextSetAllowsAntialiasing(ctx, true);
CGContextSetShouldAntialias(ctx, true);
CGContextSetFillColorWithColor(ctx, [UIColor themeColor].CGColor);
CGContextSetStrokeColorWithColor(ctx, [UIColor themeColor].CGColor);
CGContextSaveGState(ctx);
CGMutablePathRef mutablePath = CGPathCreateMutable();
CGPathMoveToPoint(mutablePath, NULL, 0, 0);
CGPathAddLineToPoint(mutablePath, NULL, 0, [self getSinPoint:0 WaveHeight:self.waveHeight]);
//Calculate the Sin funciton value to draw lines and join them into path
for (float i = 0; i <= self.bounds.size.width; i+= 1) {
NSInteger pointY = [self getSinPoint:i WaveHeight:self.waveHeight];
CGPathAddLineToPoint(mutablePath, NULL, i, pointY);
}
CGPathAddLineToPoint(mutablePath, NULL, self.bounds.size.width, 0);
CGPathCloseSubpath(mutablePath);
[[UIColor themeColor]set];
CGContextAddPath(ctx, mutablePath);
CGContextFillPath(ctx);
CGContextRestoreGState(ctx);
最佳答案
一种解决方案是使用BezierPath绘制波浪,
1.将线切成20等段
2.如果当前行索引是事件,则将控制点置于当前线段中心下方
3.如果当前行索引为奇数,则将控制点置于行中心
...
for (NSInteger i = 0; i <= self.waveCount; i++) {
CGPoint beginPoint = CGPointMake(i * self.waveWidth, pointY);
CGPoint endPoint = CGPointMake((i + 1) * self.waveWidth, pointY);
if (i%2 == 0) {
CGPoint controlPoint = [self getCenterControlPointUp:beginPoint End:endPoint];
CGPathAddQuadCurveToPoint(mutablePath, NULL, controlPoint.x, controlPoint.y, endPoint.x, endPoint.y);
}else{
CGPoint controlPoint = [self getCenterControlPointDown:beginPoint End:endPoint];
CGPathAddQuadCurveToPoint(mutablePath, NULL, controlPoint.x, controlPoint.y, endPoint.x, endPoint.y);
}
}
...
获取线段控制点的方法
//Below
-(CGPoint)getCenterControlPointDown:(CGPoint)begin End:(CGPoint)end{
return CGPointMake((begin.x + end.x)/2, (begin.y + end.y)/2 + self.waveHeight * 2);
}
//Above
-(CGPoint)getCenterControlPointUp:(CGPoint)begin End:(CGPoint)end{
return CGPointMake((begin.x + end.x)/2, (begin.y + end.y)/2 - self.waveHeight * 2);
}