ios - CALayer drawrect 抗锯齿功能不起作用

标签 ios uinavigationcontroller calayer drawrect cgcontext

enter image description here 我通过重写 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);

最佳答案

enter image description here

一种解决方案是使用 BezierPath 来绘制波浪, 1.将线剪成20等段 2.如果当前行索引为event,则获取当前线段中心下方的控制点 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);
}

关于ios - CALayer drawrect 抗锯齿功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41504383/

相关文章:

ios - Game Center 无法识别游戏

ios - 如何弹出到不在堆栈中的特定 View Controller ?

ios - 调用setNeedsDisplay并不总是触发drawLayer :inContext:

macos - Cocoa:[self.view setWantsLayer:YES] 将该 View 置于其他 subview 之上?

ios - navigationBar出现在statusBar下面

ios - 撤销按钮 Swift

ios - 为 PFobjects 实现 UISearchController 时出错

ios - UIScrollViews subview 没有在纵向到横向方向更改上调整自己的大小

ios - 以下swift代码是什么意思?

ios - 返回 SV 时 ScrollView 中的元素会移动/移动吗?