Simple Solution for Gold Challenge (no additional layer)


#1

There are many solutions to this challenge, here is my simple solution:

You just have to change 3 things:

  1. Change the line of code to make the [color=#0000FF]background color non-transparent[/color]:

---->

You do this so background COLOR of boxLayer doesn’t have any CLEAR property (cannot be seen through)

  1. Add new line of code to set [color=#0000FF]background transparent[/color]:

You do this so this layer can be seen through (different from CLEAR COLOR!). Actually, I don’t know the difference but it just works.

  1. Add code for shadow (you all know this, right ^?^):
[boxLayer setCornerRadius:20];
[boxLayer setShadowColor:[[UIColor greenColor] CGColor]];
[boxLayer setShadowOffset:CGSizeMake(10, 10)];
[boxLayer setShadowOpacity:0.8];

Here is all of my code, it’s quite messy but I hope you get the idea:

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self) {
        [self setBackgroundColor:[UIColor clearColor]];
        [self setCircleColor:[UIColor lightGrayColor]];
        
        // Create the new layer object
        boxLayer = [[CALayer alloc] init];
        
        // Give it a size
        [boxLayer setBounds:CGRectMake(0.0, 0.0, 105.0, 105.0)];
        
        // Give it a location
        [boxLayer setPosition:CGPointMake(160.0, 100.0)];
        
        // Make half-transparent red the background color for the layer
        UIColor *reddish = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1];
        
        // Get a CGColor object with the same color values
        CGColorRef cgReddish = [reddish CGColor];
        [boxLayer setBackgroundColor:cgReddish];
        [boxLayer setOpacity:0.5];
        
        // Create a UIImage
        UIImage *layerImage = [UIImage imageNamed:@"Hypno.png"];
        
        // Get the underlying CGImage
        CGImageRef image = [layerImage CGImage];
        
        // Put the CGImage on the layer
        [boxLayer setContents:(__bridge id)image];
        
        // Insert the image a bit on each side
        // http://forums.bignerdranch.com/viewtopic.php?f=235&t=4300
        [boxLayer setContentsRect:CGRectMake(-0.1, -0.1, 1.2, 1.2)];
        
        // Let the image resize (without changing the aspect ratio)
        // to fill the contentRect
        [boxLayer setContentsGravity:kCAGravityResizeAspect];
        
        [boxLayer setCornerRadius:20];
        [boxLayer setShadowColor:[[UIColor greenColor] CGColor]];
        [boxLayer setShadowOffset:CGSizeMake(10, 10)];
        [boxLayer setShadowOpacity:0.8];
        
        
        // Make it a sublayer of the view's layer
        [[self layer] addSublayer];
    }
    
    return self;
}

Result: