Skip to content

Instantly share code, notes, and snippets.

@neocsr
Created June 7, 2013 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neocsr/5729747 to your computer and use it in GitHub Desktop.
Save neocsr/5729747 to your computer and use it in GitHub Desktop.
Random context drawing in RubyMotion
class CustomView < UIView
def gradient
if @gradient
puts "Reusing gradient..."
else
puts "Creating gradient..."
colors = Pointer.new(:float, 8)
colors[0], colors[1] = 0.0/255.0, 1.0
colors[2], colors[3] = 125.0/255.0, 1.0
colors[4], colors[5] = 200.0/255.0, 1.0
locations = Pointer.new(:float, 3)
locations[0] = 0.05
locations[1] = 0.45
locations[2] = 0.95
colorSpace = CGColorSpaceCreateDeviceGray()
@gradient = CGGradientCreateWithColorComponents(colorSpace, colors, locations, 3)
CGColorSpaceRelease(colorSpace)
end
@gradient
end
def drawRect(rect)
ctx = UIGraphicsGetCurrentContext()
startPoint = CGPointMake(CGRectGetMidX(bounds), 0.0)
endPoint = CGPointMake(CGRectGetMidX(bounds), CGRectGetMaxY(bounds))
CGContextDrawLinearGradient(ctx, gradient, startPoint, endPoint, 0)
CGContextSaveGState(ctx)
CGContextTranslateCTM(ctx, 50.0, 50.0)
CGContextAddRect(ctx, CGRectMake(0.0, 0.0, 200.0, 200.0))
CGContextSetFillColorWithColor(ctx, UIColor.redColor.CGColor)
CGContextFillPath(ctx)
CGContextRestoreGState(ctx)
CGContextAddRect(ctx, CGRectMake(0.0, 0.0, 100.0, 100.0))
CGContextSetFillColorWithColor(ctx, UIColor.greenColor.CGColor)
CGContextFillPath(ctx)
CGContextSaveGState(ctx)
CGContextSetLineCap(ctx, KCGLineCapRound);
CGContextSetLineWidth(ctx, 4.0);
CGContextSetRGBStrokeColor(ctx, 0.0, 0.0, 0.0, 1.0);
CGContextSetStrokeColorWithColor(ctx, UIColor.purpleColor.CGColor);
CGContextBeginPath(ctx);
CGContextMoveToPoint(ctx, startPoint.x, startPoint.y);
CGContextAddLineToPoint(ctx, endPoint.x, endPoint.y);
CGContextStrokePath(ctx);
CGContextRestoreGState(ctx)
super
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment