Created
June 7, 2013 14:41
-
-
Save neocsr/5729747 to your computer and use it in GitHub Desktop.
Random context drawing in RubyMotion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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