Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Drawing with Code

Drawing with Code

Drawing with Code - presented at M3 Conf (http://m3conf.com) 2013

Ryan Nystrom

October 25, 2013
Tweet

More Decks by Ryan Nystrom

Other Decks in Programming

Transcript

  1. - (void)drawRect:(CGRect)rect {! // get our current drawing context! CGContextRef

    ctx = UIGraphicsGetCurrentContext();! // set the fill color! [[UIColor redColor] setFill];! // fill a rect! CGContextFillRect(ctx, rect);! } Square
  2. // draw border! [[UIColor greenColor] setStroke];! CGContextSetLineWidth(ctx, 4);! CGContextStrokeRect(ctx, rect);!

    ! // draw circle! [[UIColor redColor] setFill];! CGRect smaller = CGRectInset(rect, 20, 20);! CGContextFillEllipseInRect(ctx, smaller); Circle
  3. CGContextSetShadowWithColor(ctx, CGSizeMake(5, 10), 5, [UIColor blackColor].CGColor);! ! [[UIColor redColor] setFill];!

    CGRect smaller = CGRectInset(rect, 20, 20);! CGContextFillEllipseInRect(ctx, smaller); Shadow
  4. [[UIColor redColor] setFill];! ! CGMutablePathRef path = CGPathCreateMutable();! CGPathMoveToPoint(path, NULL,

    0, 0);! CGPathAddLineToPoint(path, NULL, rect.size.width, 0);! CGPathAddLineToPoint(path, NULL, rect.size.width / 2, rect.size.height);! CGContextAddPath(ctx, path);! ! CGContextFillPath(ctx); Path
  5. // triangle drawing! [[UIColor whiteColor] setStroke];! {! CGContextSaveGState(ctx);! [[UIColor greenColor]

    setFill];! [[UIColor blackColor] setStroke];! CGContextSetLineWidth(ctx, 4);! CGRect inner = CGRectInset(rect, 50, 50);! CGContextFillEllipseInRect(ctx, inner);! CGContextStrokeEllipseInRect(ctx, inner);! CGContextRestoreGState(ctx);! }! CGRect inner = CGRectInset(rect, 20, 20);! CGContextStrokeRect(ctx, inner); Layers
  6. CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();! CGFloat stops[] = {0, 1};! NSArray

    *colors = @[! (id)[UIColor whiteColor].CGColor,! (id)[UIColor blackColor].CGColor,! ];! CGGradientRef gradient = CGGradientCreateWithColors(colorSpace,! (__bridge CFArrayRef)(colors),! stops);! CGContextDrawLinearGradient(ctx, gradient, rect.origin, CGPointMake(0, rect.size.height), 0); Gradient