RubyMotion Tinted Image com CGBlendMode

Inspirado em http://robots.thoughtbot.com/designing-for-ios-blending-modes .

class UIImage
def tintedImageWithColor(tintColor)
UIGraphicsBeginImageContext(self.size)
tintColor
.setFill
bounds
= [[0, 0], self.size]
UIRectFill(bounds)
self.drawInRect(bounds, blendMode: KCGBlendModeHardLight, alpha: 0.8)
tintedImage
= UIImage.UIGraphicsGetImageFromCurrentImageContext
UIImage.UIGraphicsEndImageContext
tintedImage

end
end

Em seguida, use-o assim:

image = UIImage.imageNamed('image.png')
tinted_image
= image.tintedImageWithColor(UIColor.redColor)
view
= UIImageView.alloc.initWithImage(tinted_image)

Como faço isso funcionar:

A referência da Apple em CGContext declara CGBlendModes com uma primeira letra pequena. No RubyMotion você precisa mudar para uma primeira letra maiúscula.

# Will raise an error:
self.drawInRect(bounds, blendMode: kCGBlendModeHardLight, alpha: 0.8)
# Will work:
self.drawInRect(bounds, blendMode: KCGBlendModeHardLight, alpha: 0.8)

Além disso, no RubyMotion UIGraphicsEndImageContexte UIGraphicsGetImageFromCurrentImageContextnão funcionam por conta própria, é necessário anexá UIImage.-los:

# Will raise errors:
tintedImage
= UIGraphicsGetImageFromCurrentImageContext
UIGraphicsEndImageContext
# Will work:
tintedImage
= UIImage.UIGraphicsGetImageFromCurrentImageContext
UIImage.UIGraphicsEndImageContext

Tingimento feliz!