创建自定义CALayer实现

per*_*ter 4 core-animation ios

我正在尝试学习核心动画以开发某个应用程序,但我需要继承CALayer类,但是我很难让图层自己绘制.

我需要自定义CALayer有一些额外的属性和处理自定义事件(触摸等)但从一开始我实现的基本CALayer不是绘制自己,谁能告诉我我做错了什么?

我有一个MagicSquare

#import "MagicSquare.h"

@implementation MagicSquare


-(id) initWithLayer:(id)layer {
    self = [super initWithLayer:layer];


    self.bounds = CGRectMake(0, 0, 200, 200);
    self.position = CGPointMake(10,10);
    self.cornerRadius = 100;
    self.borderColor = [UIColor redColor].CGColor;
    self.borderWidth = 1.5;

    return self;
}

- (void)drawInContext:(CGContextRef)theContext
{

    NSLog(@"Drawing");
    CGMutablePathRef thePath = CGPathCreateMutable();

    CGPathMoveToPoint(thePath,NULL,15.0f,15.f);
    CGPathAddCurveToPoint(thePath,
                          NULL,
                          15.f,250.0f,
                          295.0f,250.0f,
                          295.0f,15.0f);

    CGContextBeginPath(theContext);
    CGContextAddPath(theContext, thePath );

    CGContextSetLineWidth(theContext,
                          1.0);
    CGContextSetStrokeColorWithColor(theContext,
                                     [UIColor redColor].CGColor);
    CGContextStrokePath(theContext);
    CFRelease(thePath);
}
Run Code Online (Sandbox Code Playgroud)

这就是我试图让它在主控制器上绘制的方式

@implementation BIDViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    MagicSquare *layer = [[MagicSquare alloc] initWithLayer:[CALayer layer]];

    [self.view.layer addSublayer:layer];

}
Run Code Online (Sandbox Code Playgroud)

per*_*ter 6

发现了问题.

我需要在图层上调用setNeedsDisplay,因为它不会自动绘制自己:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    MagicSquare *layer = [[MagicSquare alloc] initWithLayer:[CALayer layer]];

    [self.view.layer addSublayer:layer];

    [layer setNeedsDisplay];
}
Run Code Online (Sandbox Code Playgroud)