1

I'm trying to draw a shape into an image using UIBezierPath. I do this in my viewDidLoad, but I get a lots of invalid context errors. What am I doing wrong?

If I move it in viewDidAppear the drawing happens without any error but it isn't nice on the UI, since there's a delay between the appearance of the view and the image.

This is my function, called in viewDidLoad.

UIGraphicsBeginImageContextWithOptions(bounds.size, NO, 0.0f);

UIBezierPath* buttonBackgroundPath = [UIBezierPath bezierPath];
[buttonBackgroundPath moveToPoint: CGPointMake(16.81, 1.02)];
[buttonBackgroundPath addLineToPoint: CGPointMake(size.width, 1.02)];
[…]
[buttonBackgroundPath addLineToPoint: CGPointMake(10.66, 6.2)];
[buttonBackgroundPath closePath];

[buttonBackgroundPath fill];
[strokeColor setStroke];
buttonBackgroundPath.lineWidth = 1;
[buttonBackgroundPath stroke];*/

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;

I also tried with another approach, but it was unsuccessful in the same way (same error):

UIGraphicsBeginImageContextWithOptions(bounds.size, NO, 0.0f);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextMoveToPoint(context, 16.81, 1.02);
[…]
CGContextAddLineToPoint(context, 10.66, 6.2);
CGContextClosePath(context);

CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineWidth(context, 1.0);
CGContextSetStrokeColorWithColor(context, strokeColor.CGColor);
CGContextStrokePath(context);
CGContextSetFillColorWithColor(context, fillColor.CGColor);

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;

These are the errors I get:

Jul 13 01:46:29 <Error>: CGContextSetLineCap: invalid context 0x0
Jul 13 01:46:29 <Error>: CGContextSetLineWidth: invalid context 0x0
Jul 13 01:46:29 <Error>: CGContextSetStrokeColorWithColor: invalid context 0x0
Jul 13 01:46:29 <Error>: CGContextDrawPath: invalid context 0x0
Jul 13 01:46:29 <Error>: CGContextSetFillColorWithColor: invalid context 0x0
Jul 13 01:46:29 <Error>: CGContextMoveToPoint: invalid context 0x0
Jul 13 01:46:29 <Error>: CGContextAddLineToPoint: invalid context 0x0
Jul 13 01:46:29 <Error>: CGContextAddLineToPoint: invalid context 0x0
Jul 13 01:46:29 <Error>: CGContextAddLineToPoint: invalid context 0x0
Jul 13 01:46:29 <Error>: CGContextAddCurveToPoint: invalid context 0x0
Jul 13 01:46:29 <Error>: CGContextAddCurveToPoint: invalid context 0x0
Jul 13 01:46:29 <Error>: CGContextAddLineToPoint: invalid context 0x0
Jul 13 01:46:29 <Error>: CGContextAddLineToPoint: invalid context 0x0
Jul 13 01:46:29 <Error>: CGContextAddCurveToPoint: invalid context 0x0
Jul 13 01:46:29 <Error>: CGContextClosePath: invalid context 0x0
4

2 に答える 2

4

私はあなたがbounds何らかの見方から得ていると思います。ビューはまだ現在の画面に合わせてサイズ変更されていないため、 メソッドviewDidLoadviewWillAppear:メソッドはビューの境界を調べるには時期尚早です。

boundsビューはで見ることができますviewDidLayoutSubviews

于 2013-07-13T00:47:53.880 に答える