Last Updated: February 25, 2016
·
2.208K
· bolomichelin

Gold Challenge : Chapter 6 - iOS Programming: The Big Nerd Ranch Guide (3rd Edition)

I am leaning IOS at the moment with "iOS Programming: The Big Nerd Ranch Guide"
Most chapters in this book finished with 3 challenges - Bronze - Silver and Gold.
I will share with you my code for Gold Challenges. :

  • draw a image
  • add circle with border and shadow
  • mask the image with circle
  • add gradien in circle

my code

- (void)drawRect:(CGRect)rect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    UIImage *img = [UIImage imageNamed:@"Icon@2x.png"];
    CGRect bounds = [self bounds];
    CGPoint center;
    center.x = bounds.origin.x + bounds.size.width / 2.0;
    center.y = bounds.origin.y + bounds.size.height / 2.0;
    float maxRadius = hypot(bounds.size.width, bounds.size.height) / 3.0;

    CGContextSaveGState(ctx);
    CGContextAddArc(ctx, center.x, center.y, maxRadius, 0.0, M_PI * 2.0, YES);
    CGContextSetShadowWithColor(ctx, CGSizeMake(0, 1), 2, [[UIColor blackColor] CGColor]);
    CGContextStrokePath(ctx);
    CGContextRestoreGState(ctx);
    CGContextAddArc(ctx, center.x, center.y, maxRadius, 0.0, M_PI * 2.0, YES);
    CGContextClip(ctx);

    [img drawInRect:bounds];
    //Gradient related variables
    CGGradientRef myGradient;
    CGColorSpaceRef colorSpace  = CGColorSpaceCreateDeviceRGB();
    CGFloat colorList[] ={
        173.0/255.0, 216.0/255.0,230.0/255.0, 1.0, //red, green, blue, alpha
        1.0, 1.0, 1.0, 0.5};

    CGFloat locationList[3] = {0.0, 1};
    myGradient = CGGradientCreateWithColorComponents(colorSpace, colorList,locationList, 2);
    //Paint a linear gradient
    CGPoint startPoint, endPoint;
    startPoint.x = bounds.size.width / 2.0; // center
    startPoint.y = 0;
    endPoint.x =  bounds.size.width / 2.0;
    endPoint.y = bounds.size.height / 2.0;
    //CGContextClip(ctx);
    CGContextDrawLinearGradient(ctx, myGradient, startPoint, endPoint,0);
}