#!ruby
# TextEffect - path library sample
#
# author: Kazuhiro Yoshida
# mailto: moriq@moriq.com
# license: Ruby
#
# based on DHGL 1.2 - Chapter6\6-2\TextEffect
# http://www.asahi-net.or.jp/~HA3T-NKMR/DGS/ 

require 'phi'; include Phi
require 'path'

form = Component._load open('TextEffect.afm', 'rb').read
form.text_effect_panel.double_buffered = true

# 赤に白い水玉
def mizutama_bitmap
  bmp = Bitmap.new
  bmp.width = 8
  bmp.height = 8
  bmp.canvas.brush.color = CL_RED
  bmp.canvas.fill_rect(Rect.new(0, 0, 8, 8))
  bmp.canvas.pen.color = CL_WHITE
  bmp.canvas.brush.color = CL_WHITE
  bmp.canvas.ellipse(1, 1, 7, 7)
  bmp
end
mizutama = mizutama_bitmap

def text_path(canvas)
  # パス情報の生成
  Path.open(canvas) do |cv|
    # 70pt Bold の文字列のパス情報を作成する
    cv.font.size = 70
    cv.font.style = [FS_BOLD]
    cv.brush.style = BS_CLEAR
    cv.text_out(30, 30, 'Text Effect')
  end
  Path.flatten(canvas)  # パスを直線の集まりに直す
  path = Path.new
  path.load(canvas)  # パス情報を吸い上げる
  path
end
path = text_path(form.canvas)

  text_height = form.canvas.text_height('Text Effect')
  twisted_path = Path.new

form.text_effect_panel.paint_box.on_paint = proc do
  GC.disable
  
  cy = 30 + text_height/2
  ratio = 2*Math::PI*form.twist_tb.position/100/path.count
  
  # パス情報をコピーする
  twisted_path.assign(path)
  
  # パス情報にひねりを加える
  path.count.times do |i|
    p = twisted_path.get_point(i)
    p.point.y = ((p.point.y - cy) * 
      Math.cos((p.point.x - 30)*ratio) + 
      cy).to_i
    twisted_path.set_point(i, p)
  end
  
  cv = form.text_effect_panel.paint_box.canvas
# cv = twisted_path.canvas
  cv.pen.color = CL_YELLOW  # ペン色=黄色 ペン幅=2
  cv.pen.width = 2
  cv.brush.bitmap = mizutama
  
  # ひねった文字列を描く
  twisted_path.draw_stroke_and_fill(cv)
  
  GC.start
end

form.twist_tb.on_change = proc do
  form.text_effect_panel.paint_box.invalidate
end

form.show
mainloop
