3

我试图通过子类化使用 CALayer 进行绘制。我知道有一些关于我已经看过其中大部分的帖子并遵循了给出的解决方案但没有成功。比如设置帧大小。这是代码。提前需要一些帮助

//
//  NewView.m
//  layerPractise


#import "NewView.h"
#import "QuartzCore/QuartzCore.h"
#import "NewLayer.h"
#import "NewLayer2.h"

@interface NewView() {
//  NSMutableArray *_normalizedValues;

}
@end

@implementation NewView
@synthesize _containerLayer;

@synthesize layer,shouldAddNewLayer;

-(void)doInitialSetup {
    self._containerLayer = [CALayer layer];
    [_containerLayer setFrame:self.frame];
    [self.layer addSublayer:self._containerLayer];
//    [_containerLayer retain];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self doInitialSetup];
    }

    return self;
}

-(id)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self doInitialSetup];
    }

    return self;
}


- (void)addCustomLayer{



    NewLayer *newLayer = [NewLayer layer];

    newLayer.frame = self.bounds;

    [_containerLayer addSublayer:newLayer];
    [newLayer setNeedsDisplay];


}



// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.

//- (void)drawRect:(CGRect)rect
//{
//    // Drawing code
//}


@end

和 NewLayer 类

- (id)initWithLayer:(id)layer{

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

    }

    return self;
}

- (id)init {
    self = [super init];
    if (self) {

        self.frame = CGRectMake(0, 0, 500, 500);
        self.delegate = self;
        CGRect r = self.frame;
        [self setNeedsDisplay];
    }

    return self;
}

+ (BOOL)needsDisplayForKey:(NSString *)key {

    [super needsDisplayForKey:key];

}

- (void)drawInContext:(CGContextRef)ctx{

    CGContextMoveToPoint(ctx, 100, 100);
    CGContextAddLineToPoint(ctx, 500, 800);
    CGContextSetStrokeColorWithColor(ctx, [UIColor blackColor].CGColor);

    CGContextDrawPath(ctx, kCGPathStroke);


}
4

1 回答 1

3

addCustomLayer方法永远不会被调用。在doInitialSetup一个层被创建但它的类型是CALayer而不是你的自定义子类NewLayer

于 2013-03-09T20:21:35.723 回答