简体   繁体   中英

Bezier path not visible in view

I copied the code below from the Stanford ios7 course for adding a Bezier path to a view. however, when I included this code in ViewDidLoad it didn't show anything on the screen

 UIBezierPath *path = [[UIBezierPath alloc] init];
    [path moveToPoint:CGPointMake(75, 10)];
    [path addLineToPoint: CGPointMake(160, 150)];
    [path addLineToPoint:CGPointMake(10, 150)];
    [[UIColor whiteColor] setStroke];
    [[UIColor whiteColor] setFill];
    [path stroke];
    [path fill];

Afterwards, I added this log statement NSLog(@"path: %@", path); which prints this ominous error message.

This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.

Can you explain what I am doing wrong?

I have accomplished this by creating a CAShapeLayer, and adding it as a sublayer of the view's layer. What's neat is that you can use the UIBezierPath's CGPath attribute to set up the layer.

    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.path = path.CGPath;
    layer.strokeColor = [UIColor whiteColor].CGColor;
    [self.view.layer addSublayer:layer];

The error message is exactly correct. You are using drawing commands, but you are not inside a drawing (graphics) context. Hence your commands are just thrown away (and are bad).

You should give drawing commands only when you are within a graphics context. There are two main such situations:

  • You're in a UIView subclass's drawRect: .

  • You've created an image graphics context with UIGraphicsBeginImageContextWithOptions .

You are in neither situation. You can make a bezier path object, constructing the path , but you cannot draw the object; commands like setStroke and stroke are thus illegal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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