3 回答

TA貢獻1784條經驗 獲得超2個贊
像這樣平滑曲線的最簡單方法是使用貝塞爾曲線而不是直線段。有關其背后的數學信息,請參閱本文(指向此答案),該文章描述了如何計算平滑通過多個點的曲線所需的曲線。
我相信Core Plot框架現在可以平滑繪圖的曲線,因此您可以查看那里用于實現這種平滑處理的代碼。
這沒有什么神奇的,因為這些平滑例程是快速且相對容易實現的。

TA貢獻1812條經驗 獲得超5個贊
CGPoint midPoint(CGPoint p1, CGPoint p2)
{
return CGPointMake((p1.x + p2.x) * 0.5, (p1.y + p2.y) * 0.5);
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
previousPoint1 = [touch previousLocationInView:self];
previousPoint2 = [touch previousLocationInView:self];
currentPoint = [touch locationInView:self];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
previousPoint2 = previousPoint1;
previousPoint1 = [touch previousLocationInView:self];
currentPoint = [touch locationInView:self];
// calculate mid point
CGPoint mid1 = midPoint(previousPoint1, previousPoint2);
CGPoint mid2 = midPoint(currentPoint, previousPoint1);
UIGraphicsBeginImageContext(self.imageView.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[self.imageView.image drawInRect:CGRectMake(0, 0, self.imageView.frame.size.width, self.imageView.frame.size.height)];
CGContextMoveToPoint(context, mid1.x, mid1.y);
// Use QuadCurve is the key
CGContextAddQuadCurveToPoint(context, previousPoint1.x, previousPoint1.y, mid2.x, mid2.y);
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineWidth(context, 2.0);
CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0);
CGContextStrokePath(context);
self.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}

TA貢獻1772條經驗 獲得超5個贊
我真的很喜歡這個話題。感謝所有實現,尤其是KrzysztofZab?ocki和Yu-Sen Han。我已經修改了Yu-Sen Han的版本,以便根據平移速度(實際上是最后一次觸摸之間的距離)來更改線條的粗細。我還實現了點繪制(對于touchBegan和touchEnded位置彼此靠近),結果如下:
為了定義線寬,我選擇了距離的函數:
(不要問我為什么……雖然很合適,但我敢肯定您會找到更好的一個)
CGFloat dist = distance(previousPoint1, currentPoint);
CGFloat newWidth = 4*(atan(-dist/15+1) + M_PI/2)+2;
還有一個提示。為確保厚度平滑變化,我根據上一段的厚度和自定義系數限制了邊界:
self.lineWidth = MAX(MIN(newWidth,lastWidth*WIDTH_RANGE_COEF),lastWidth/WIDTH_RANGE_COEF);
- 3 回答
- 0 關注
- 683 瀏覽
添加回答
舉報