开发者

Making a layer structure for a drawing application

In relation to question an eralier question of mine, I have tried and fail开发者_JAVA百科ed to create a class with a NSMuttableArray member variable holding CALayerRefs. Can someone please guide me on how to do that. What I want to do is basically create CALayerRefs or CGLayerRefs or whatever, push them into my layers variable, and then, when I need them, fetch, use their context and finally draw/hide/show/delete them.

I turn to you, guys, because apparently, there is few to none information on the net on working with layers and Quartz on an advanced level. Everybody uses the layers right away, no management needed, no member variables.

Thank you.


Here's some working code for custom view I wrote in few minutes, hope it helps. It creates 10 green layers, and animates them each second to different locations.

MBLineLayerDelegate *lineLayerDelegate;
@property (nonatomic, retain) NSMutableArray *ballLayers;

- (void)awakeFromNib
{
    self.ballLayers = [NSMutableArray array];
    lineLayerDelegate = [[MBLineLayerDelegate alloc] init];
    for (NSUInteger i = 0; i < 10; i++) {
        CALayer *ball = [CALayer layer];
        CGFloat x = self.bounds.size.width * (CGFloat)random()/RAND_MAX;
        CGFloat y = self.bounds.size.height * (CGFloat)random()/RAND_MAX;
        ball.frame = CGRectMake(x, y, 20, 20);
        ball.backgroundColor = [UIColor greenColor].CGColor;
        ball.delegate = lineLayerDelegate;
        [self.layer addSublayer:ball];
        [self.ballLayers addObject:ball];
    }

    [self performSelector:@selector(animateBallsToRandomLocation) withObject:nil afterDelay:0];
}

- (void)animateBallsToRandomLocation
{
    for (CALayer *layer in self.ballLayers) {
        CGFloat x = self.bounds.size.width * (CGFloat)random()/RAND_MAX;
        CGFloat y = self.bounds.size.height * (CGFloat)random()/RAND_MAX;
        layer.position = CGPointMake(x, y);
    }
    [self performSelector:@selector(animateBallsToRandomLocation) withObject:nil afterDelay:1];
}

Here's some code for CALayer's delegate that draws a line:

@interface MBLineLayerDelegate : NSObject {
}
- (void)drawLayer:(CALayer*)layer inContext:(CGContextRef)ctx;
@end

@implementation MBLineLayerDelegate

- (void)drawLayer:(CALayer*)layer inContext:(CGContextRef)context
{
        CGRect rect = layer.bounds;
        CGContextSaveGState(context);

        CGContextTranslateCTM(context, 0.0, rect.size.height);
        CGContextScaleCTM(context, 1.0, -1.0);
        CGContextSetAllowsAntialiasing(context, YES);
        CGContextSetShouldAntialias(context, YES);

        CGContextMoveToPoint(context, 0, 0);
        CGContextAddLineToPoint(context, rect.size.width, rect.size.height);

        CGContextRestoreGState(context);
}

@end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜