Challenge: my version with delegate


#1

This is my coding. What is added are in bold. Please correct or improve this version. Thank you.

HypnosisView.h

@interface HypnosisView : UIView
{
CALayer *boxLayer;
float xShift, yShift;
UIColor *stripeColor;
CGPoint boxLayerPos;
}

@property (nonatomic, assign) float xShift;
@property (nonatomic, assign) float yShift;
@property (nonatomic, readonly) CALayer *boxLayer;
@property (nonatomic, assign) CGPoint boxLayerPos;

@end


HypnosisView.m

@implementation HypnosisView
@synthesize xShift, yShift, boxLayer, boxLayerPos;

  • (id)initWithFrame:(CGRect)r
    {
    self = [super initWithFrame:r];

    if (self) {
    stripeColor = [[UIColor lightGrayColor] retain];

      boxLayer = [[CALayer alloc] init];
      [boxLayer setBounds:CGRectMake(0.0, 0.0, 85.0, 85.0)];
      [boxLayer setPosition:CGPointMake(160.0, 100.0)];
      UIColor *reddish = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.5];
      CGColorRef cgReddish = [reddish CGColor];
      [boxLayer setBackgroundColor:cgReddish];
      
      [[self layer] addSublayer];
      [boxLayer release];
    

    }
    return self;
    }

  • (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
    {
    UITouch *t = [touches anyObject];
    CGPoint p = [t locationInView:self];
    [self setBoxLayerPos:p];
    [CATransaction begin];
    [CATransaction setDisableActions:YES];
    [boxLayer setPosition:p];
    [CATransaction commit];
    [boxLayer setNeedsDisplay];

    }


HypnosisViewController.h

@class HypnosisView;

@interface HypnosisViewController : UIViewController
{
HypnosisView *hv;
}

@end


HypnosisViewController.m

[b]- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
{
if (layer == [hv boxLayer] ) {

    CGPoint boxLayerPosition = [hv boxLayerPos];
    float boxLayerYPos = boxLayerPosition.y;
      
    float boxAlpha = fabsf(1 - (boxLayerYPos / 400));  
    NSLog(@"boxAlpha = %f", boxAlpha);

    UIImage *layerImage = [UIImage imageNamed:@"Hypno.png"];
    CGRect boundingBox = CGContextGetClipBoundingBox(ctx);
    CGContextSetAlpha(ctx, boxAlpha); 
    CGContextDrawImage(ctx, boundingBox, [layerImage CGImage]);
}

}
[/b]

  • (void)loadView
    {
    hv = [[HypnosisView alloc] initWithFrame:CGRectZero];
    [hv setBackgroundColor:[UIColor whiteColor]];
    [self setView:hv];

[[hv boxLayer] setDelegate:self];
[hv setBoxLayerPos:[[hv boxLayer] position]];
[[hv boxLayer] setNeedsDisplay];
[hv release];

}