这是Ruby代码:
require 'rmagick'
include Magick
img = Image.new(300, 300)
draw = Draw.new
draw.line(0, 150, 300, 150)
draw.line(150, 0, 150, 300)
# for each of known gravity constants...
%w[NorthWestGravity NorthGravity NorthEastGravity WestGravity CenterGravity EastGravity SouthWestGravity SouthGravity SouthEastGravity].
each{|g|
# set gravity to this value...
draw.gravity Magick.const_get(g)
# ...and draw text with this constant name
draw.text 150, 150, g
}
draw.draw(img)
img.write('tmp/gravity.png')
这是它产生的图像:
对于SouthEast / NorthWest和类似的重力结果如预期的那样(文本接近150,150,向所需方向移动)。但是对于南方,北方和其他人的结果真的很奇怪。
就我从代码中可以理解的那样,RMagick只是将重力和文本命令转换为相应的ImageMagick绘图基元,因此,我认为它在ImageMagick的重力概念中是我无法获得的。
这是什么?..
答案 0 :(得分:2)
我认为ImageMagick的重力概念中有些东西是我无法获得的。
这是什么?..
了解正在发生的事情的关键是找到 CenterGravity 文字。
150px 向左移动, 150px 向下移动。
现在比较 NorthWestGravity 位置。
还翻译左和右分别按 150px 。看到一个趋势?
你的问题在于这一行......
draw.text 150, 150, g
Magick::Draw
API映射到MVG规范。使用Magick::Draw.push
& Magick::Draw.pop
来控制绘图环境。
要设置要绘制的文本的原点,您需要在评估文本/类型指标后计算位置。
实施例
require 'rmagick'
include Magick
img = Image.new(300, 300) {
self.background_color = "palegreen"
}
draw = Draw.new
dotes = Draw.new # Dotes added for point of origin
dotes.fill = "red"
cursor = 1
# for each of known gravity constants...
%w[NorthWestGravity NorthGravity NorthEastGravity WestGravity CenterGravity EastGravity SouthWestGravity SouthGravity SouthEastGravity].
each{|g|
offsetX = 150
offsetY = cursor * 25
dotes.circle offsetX, offsetY, offsetX+2, offsetY+2
# Get metrics of text
metrics = draw.get_type_metrics(img, g)
# Full width
if %w[NorthWestGravity WestGravity SouthWestGravity].include? g then
offsetX -= metrics[:width]
end
# Full height
if %w[SouthWestGravity SouthGravity SouthEastGravity].include? g then
offsetY += metrics[:ascent]
end
# Half width
if %w[NorthGravity SouthGravity CenterGravity].include? g then
offsetX -= metrics[:width] / 2
end
# Half height
if %w[WestGravity CenterGravity EastGravity].include? g then
offsetY += metrics[:ascent] / 2
end
draw.text offsetX, offsetY, g
cursor += 1
}
dotes.draw(img)
draw.draw(img)
img.write('output.png')