• Download Gist
http://www.quora.com/How-can-I-render-a-transparent-gradient-with-RMagick
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#!/usr/bin/env ruby
 
##
# This is an answer to http://www.quora.com/How-can-I-render-a-transparent-gradient-with-RMagick
# and is inspired heavily from http://rmagick.rubyforge.org/web2/web2.html
##
 
require 'rubygems'
require 'RMagick'
 
include Magick
 
rows = 480
cols = 640
 
# start line is across the top, so vertical gradient
# start with white (fully opaque) and end with black (fully transparent)
#mask_grad = GradientFill.new(0, 0, cols, 0, '#ffffff', '#000000')
 
# to go from 0.3 to 0.7, try
mask_grad = GradientFill.new(0, 0, cols, 0, 'rgb(30%, 30%, 30%)', 'rgb(70%, 70%, 70%)')
 
 
mask_img = Magick::Image.new(cols, rows, mask_grad)
#mask_img.matte = false # ignore alpha channel (doesn't seem to be necessary for this)
 
img = Magick::Image.new(cols, rows) do
self.background_color = "red" # just for testing to make seeing easier
#self.background_color = "black"
end
#img.matte = true # respect the alpha channel (doesn't seem to be necessary for this)
 
img.composite!(mask_img, CenterGravity, CopyOpacityCompositeOp)
 
img.write('gradient.png')

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.