Domanda

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:

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

È stato utile?

Soluzione

Put the code you have in viewDidLoad (except [super viewDidLoad]) into drawRect method. UIGraphicsGetCurrentContext() needs to be called within drawRect method in order to know whitch is the current context.

EDIT:

also put:

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

inside while loop. And before while loop set the stroke color:

[[UIColor redColor] setStroke];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top