简体   繁体   English

手动绘制贝塞尔曲线

[英]Drawing Bezier curve manually

I am trying to create a Bezier curve manually in this way: 我正在尝试以这种方式手动创建贝塞尔曲线:

- (void)drawBezierFrom:(CGPoint)from to:(CGPoint)to controlA:(CGPoint)a controlB:(CGPoint)b sections:(NSUInteger)cnt color:(NSUInteger)color
{
float qx, qy;
float q1, q2, q3, q4;
int lastx = - 1, lasty;
int plotx, ploty;
float t = 0.0;

while (t <= 1)
{
    q1 = t*t*t*-1 + t*t*3 + t*-3 + 1;
    q2 = t*t*t*3 + t*t*-6 + t*3;
    q3 = t*t*t*-3 + t*t*3;
    q4 = t*t*t;

    qx = q1*from.x + q2*a.x + q3*to.x + q4*b.x;
    qy = q1*from.y + q2*a.y + q3*to.y + q4*b.y;

    plotx = round(qx);
    ploty = round(qy);

    /*if (lastx != -1)
        [self drawLineFrom:NSMakePoint(lastx, lasty) to:NSMakePoint(plotx, ploty) color:color];
    else
        [self drawLineFrom:NSMakePoint(from.x, from.y) to:NSMakePoint(plotx, ploty) color:color];*/

    lastx = plotx;
    lasty = ploty;
    t = t + (1.0/(cnt + 0.0f));
}
//[self drawLineFrom:NSMakePoint(lastx, lasty) to:NSMakePoint(to.x, to.y) color:color];
[self drawLineFromCoordX:lastx andY:lasty toPointWithCoordsX:to.x andY:to.y];
}

-(void)drawLineFromCoordX:(int)x andY:(int)y toPointWithCoordsX: (int)fx andY: (int)fy{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextMoveToPoint(context, x,y);
CGContextAddLineToPoint(context, fx,fy);
CGContextStrokePath(context);
}

Calling the methods in the viewDidLoad: 调用viewDidLoad中的方法:

CGPoint fromPoint = CGPointMake(10, 10);
CGPoint toPoint = CGPointMake(100, 10);
CGPoint controlA = CGPointMake(50, 50);
CGPoint controlB = CGPointMake(60, 60);

[self drawBezierFrom:fromPoint to:toPoint controlA:controlA controlB:controlB sections:10     color:4];

EDIT: 编辑:

I did exactly what you did: 我确实做了你所做的:

-(void)drawRect:(CGRect)rect{
CGPoint fromPoint = CGPointMake(10, 10);
CGPoint toPoint = CGPointMake(100, 10);
CGPoint controlA = CGPointMake(50, 50);
CGPoint controlB = CGPointMake(60, 60);

[self drawBezierFrom:fromPoint to:toPoint controlA:controlA controlB:controlB sections:10 color:4];
}

and kept everything else the same, and it still doesn't work 并保持其他所有内容不变,但仍然无法正常工作

Put the code you have in viewDidLoad (except [super viewDidLoad]) into drawRect method. 将您在viewDidLoad中拥有的代码([super viewDidLoad]除外)放入drawRect方法。 UIGraphicsGetCurrentContext() needs to be called within drawRect method in order to know whitch is the current context. 需要在drawRect方法中调用UIGraphicsGetCurrentContext(),以便知道哪些是当前上下文。

EDIT: 编辑:

also put: 还放:

[self drawLineFromCoordX:lastx andY:lasty toPointWithCoordsX:to.x andY:to.y];

inside while loop. 在while循环内。 And before while loop set the stroke color: 在while循环之前设置笔触颜色:

[[UIColor redColor] setStroke];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM