创建自定义CALayer实现

时间:2012-09-01 23:11:36

标签: ios core-animation

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

我需要自定义CALayer来获得一些额外的属性并处理自定义事件(触摸等)但是从一开始我实现的基本CALayer并没有自己绘制,有人能告诉我我做错了吗? / p>

我有一个 幻方

#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);
}

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

@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];

}

1 个答案:

答案 0 :(得分: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];
}