Skip to content

Instantly share code, notes, and snippets.

@hiroyuki-sato
Last active April 7, 2020 09:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hiroyuki-sato/a0639cc9d4e10acb1bed to your computer and use it in GitHub Desktop.
Save hiroyuki-sato/a0639cc9d4e10acb1bed to your computer and use it in GitHub Desktop.
Pango 複数フォント日本語レイアウト
#!/usr/bin/env ruby
# encoding: ascii-8bit
require 'cairo'
require 'pango'
##### Cairo定義 ###############################################
format = Cairo::FORMAT_ARGB32
width = 1200 #縦ドット
height = 200 #横ドット
next_x = 0
surface = Cairo::ImageSurface.new(format, width, height)
context = Cairo::Context.new(surface)
##### Pango定義 ###############################################
layout = context.create_pango_layout
##### 氏名書き出し ###############################################
layout.text = "佐藤博之"
layout.set_font_description(Pango::FontDescription.new("IPA P明朝 64"))
layout.wrap = Pango::WRAP_CHAR # 文字単位
extents_rect = layout.extents[1]
text_width = extents_rect.width / Pango::SCALE
text_height = extents_rect.height / Pango::SCALE
puts "width:#{text_width}, height:#{text_height}"
#start_y = 30
context.translate(0, 0)
context.show_pango_layout(layout)
# ビットマップファイル出力
surface.write_to_png("pango.png")
# 次の文字の書き出し位置
next_x = text_width + 50
##### 氏名書き出し2 ###############################################
layout.text = "佐藤博之"
layout.set_font_description(Pango::FontDescription.new("源真ゴシック 64"))
layout.wrap = Pango::WRAP_CHAR # 文字単位
extents_rect = layout.extents[1]
text_width = extents_rect.width / Pango::SCALE
text_height = extents_rect.height / Pango::SCALE
puts "width:#{text_width}, height:#{text_height}"
##############################
#context.translate(next_x, -23)
context.translate(next_x, 0)
# Pango文字(牧野文則)出力
context.show_pango_layout(layout)
# ビットマップファイル出力
surface.write_to_png("pango.png")

出力

width:340, height:87
width:340, height:120

サマリ

FONT Width Height
IPA 64px 340 87
源真64px 340 120
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment