#!ruby -Ku # -*- mode: ruby; coding: utf-8 -*- # Last updated: <2017/04/17 00:19:10 +0900> # # cairo(rcairo) + DXRuby の描画テストその3 # png出力して読み込み直す方法と、 # サーフェイスデータを取り出して変換する方法の # どちらが速いのか比較してみる require 'cairo' require 'stringio' require 'dxruby' require 'benchmark' # DXRubyのImageに変換。StringIOを使う版 def convert_image(w, h, surface) temp = StringIO.new("", 'w+') surface.write_to_png(temp) temp.rewind img = Image.loadFromFileInMemory(temp.read) temp.close return img end # DXRubyのImageに変換。StringIOを使わない版 def convert_image2(w, h, surface) dst = [] src = surface.data.unpack("L*") src.each do |d| dst << ((d >> 24) & 0x0ff) # a dst << ((d >> 16) & 0x0ff) # r dst << ((d >> 8) & 0x0ff) # g dst << (d & 0x0ff) # b end return Image.createFromArray(w, h, dst) end srand(0) w, h = 640, 480 img = nil Benchmark.bm(15) do |x| surface = Cairo::ImageSurface.new(Cairo::FORMAT_ARGB32, w, h) x.report("cairo draw") { ct = Cairo::Context.new(surface) 512.times do ct.set_source_rgb(rand, rand, rand) radius = h * rand * 0.1 ct.arc(w * rand, h * rand, radius, 0, 2 * Math::PI) ct.fill end } x.report("use StringIO") { img = convert_image(w, h, surface) } x.report("not StringIO") { img = convert_image2(w, h, surface) } end # DXRubyで表示 Window.bgcolor = [64, 64, 64] Window.loop do break if Input.keyPush?(K_ESCAPE) Window.draw(0, 0, img) end