My company has started building a new time tracking applications for mac users, focusing mostly on freelancers. During one of our mock up sessions I commented that it might be nice to put a gradient background behind the view. So I took it upon myself to figure out how I would add a gradient background using RubyCocoa.
First off, I did a quick google search for "cocoa gradient background custom view", and I found a couple of interesting sites:
1) Cocoa Background Tutotorial 1.1
2) Pimp My Code: Part 3 Gradient Table Views
I decided to focus on the second post since this was more inline with what I was trying to do, and it didn't hurt that it was written by Wil Shipley. As a side note, if you have never checked out his blog Call Me Fishmeal you really should.
Now that I had my example and I knew what I wanted to do it was time to port the code over to RubyCocoa so I could start playing with it. Well after 3 hours of looking at API's and c functions, I only made it about 1/2 way before I had to call it a night. About an hour into my coding the next morning, I was looking at an API when I ran across a link to the companion document, the "Cocoa Drawing Guide". I figured I had nothing to lose so I took a quick look. Upon perusing the contents in the left side, I couldn't believe my eyes. Right there in the "Related Reference" section was a link to the NSGradient class.
After some swearing, crying and general shock that I had missed this in my searching, I felt excitied and ready to code. Below is the RubyCocoa code for my first quick test project using the NSGradient class.
Rounded Textured Button With A Gradient Fill: My Custom Draw Method
def drawRect(rect)
newSize = OSX::NSRect.new([(rect.x + 2), (rect.y+1)],[(rect.width - 4),(rect.height-3)])
clipShape = OSX::NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius(newSize,6,(rect.height/2))
aGradient = OSX::NSGradient.alloc.initWithStartingColor_endingColor(OSX::NSColor.whiteColor,OSX::NSColor.grayColor)
aGradient.drawInBezierPath_angle(clipShape,90);
self.attributedTitle.drawInRect(newSize)
end
Class References:
NSGradient
NSBezierPath
Lastly some things that I ran across when making this example:
1. Make sure you are looking at the latest api's from apple. At one point I wasted about 20 min looking at an older version of the NSBezierPath api.
2. Make sure to read the Cocoa Drawing Guide
3. Once you get a base example working, play with it and try to change things like the text color or the path's line width.
Comments