2013-03-14 88 views
0

Alphabet 繪製CGPath UIBezierCurve

大家好,我尋找到的我怎麼能畫出像一個圖中above.I形狀方面一直在尋找和閱讀,但得到稍微混亂的曲線是如何使用繪製UIBezierPath。我發現真的nice code它使用CAShapeLayer與動畫畫線。

代碼到目前爲止,我是:

@synthesize animationLayer = _animationLayer; 
@synthesize pathLayer = _pathLayer; 
@synthesize penLayer = _penLayer; 


- (void) setupDrawingLayer 
{ 
    if (self.pathLayer != nil) { 
    [self.penLayer removeFromSuperlayer]; 
    [self.pathLayer removeFromSuperlayer]; 
    self.pathLayer = nil; 
    self.penLayer = nil; 
    } 


CGPoint upperCurve = CGPointMake(101, 100); 
CGPoint lowerCurve = CGPointMake(224,200); 



UIBezierPath *path = [UIBezierPath bezierPath]; 
path.lineCapStyle = kCGLineCapRound; 
path.miterLimit = -10.0f; 
path.lineWidth = 10.0f; 

[path moveToPoint:lowerCurve]; 
[path addQuadCurveToPoint:upperCurve controlPoint:lowerCurve]; 




CAShapeLayer *pathLayer = [CAShapeLayer layer]; 

pathLayer.frame = self.animationLayer.bounds; 

pathLayer.path = path.CGPath; 

pathLayer.strokeColor = [[UIColor blackColor] CGColor]; 

pathLayer.fillColor = nil; 

pathLayer.lineWidth = 10.0f; 

pathLayer.lineJoin = kCALineJoinBevel; 

[self.animationLayer addSublayer:pathLayer]; 

self.pathLayer = pathLayer; 

} 


-(void) startAnimation 
{ 
[self.pathLayer removeAllAnimations]; 


CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"]; 
pathAnimation.duration = 10.0; 
pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f]; 
pathAnimation.toValue = [NSNumber numberWithFloat:1.0f]; 
[self.pathLayer addAnimation:pathAnimation forKey:@"strokeEnd"]; 

} 

- (void)viewDidLoad 
{ 
[super viewDidLoad]; 

self.animationLayer = [CALayer layer]; 
self.animationLayer.frame = CGRectMake(20.0f, 64.0f, 
             CGRectGetWidth(self.view.layer.bounds) - 40.0f, 
             CGRectGetHeight(self.view.layer.bounds) - 84.0f); 
[self.view.layer addSublayer:self.animationLayer]; 

[self setupDrawingLayer]; 
[self startAnimation]; 
} 

回答

1

我解決這類問題的方法是繪製在繪圖程序形狀如插圖。這清楚地顯示了貝塞爾曲線點需要走的路線,以便獲得我之後的曲線。

1

UIBezierPath通常以moveToPoint開頭來設置曲線的起始點。那麼它的後跟任意數量的使用這些方法的曲線段: - addLineToPoint: - addArcWithCenter:半徑:由startAngle:endAngle:順時針方向: - addCurveToPoint:controlPoint1:controlPoint2: - addQuadCurveToPoint:控制點:

你沒」特別說明你有什麼問題,所以我要做一個跳躍,並且假設它是addCurveToPoint:controlPoint1:controlPoint2,你正在努力。

通過此調用添加的細分將繪製從最近添加或從第一個參數移動到曲線的點開始的細分。它的波動是由控制點決定的。

理解它如何起伏的最簡單方法是想象連接第一個點(在前一個方法調用中建立)到第一個控制點(讓我們稱之爲控制點線段1)的線,另一條線連接第一個點參數(要添加的段的終點)到第二個控制點(我們稱該控制點線段2)。

起點處的貝塞爾曲線與控制點線段1相切。它與曲線末端的控制點線段2相切。

因此,如果要繪製多條貝塞爾曲線以形成平滑線,則需要確保一條曲線的控制點線段2的斜率與控制點線的斜率相同下一條連接到它的曲線的段1。

從起點到第一個控制點的距離和到第二個控制點的終點決定曲線的曲率。

我的一個朋友以這種方式想象它。設想一艘太空船從A點行駛到B點。太空船的航向由控制點線段1的斜率確定,並由其長度決定。標題逐漸改變爲控制點線段2的斜率。同時,速度逐漸改變爲控制點線段2的長度。在太空船到達B點時,它正在與該點相切分割。