CALayer drawrect 抗锯齿没用

CALayer drawrect Anti-Aliasing didn't worked

我用override 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.cut 将行分成段如20 2.if当前行索引为事件,获取当前段中心下方的控制点 3.if当前行索引为奇数,则控制点在行的中心上

...
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);
}