Skip to content

Instantly share code, notes, and snippets.

@andymeneely
Last active April 30, 2018 05:16
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 andymeneely/f21a39fce8008459da6f9ec52faea38f to your computer and use it in GitHub Desktop.
Save andymeneely/f21a39fce8008459da6f9ec52faea38f to your computer and use it in GitHub Desktop.
Carve out arbitrary space inside of Pango text to draw on the surface.
require 'cairo'
require 'pango'
cxt = Cairo::Context.new(Cairo::ImageSurface.new(200,200))
puts "Our outer CR is: #{cxt.inspect}"
cxt.set_source_color('white')
cxt.paint
cxt.set_source_color('red')
extent_width = 200
extent_height = 200
cxt.rounded_rectangle(0,0,extent_width,extent_height,0)
cxt.stroke
cxt.set_source_color('black')
text = 'Hello, World! This is a very long set of text'
layout = cxt.create_pango_layout
layout.text = text
layout.width = extent_width * Pango::SCALE
layout.height = extent_height * Pango::SCALE
layout.wrap = :word_char
ico_w = 10
ico_h = 20
layout.context.set_shape_renderer do |cr, att, do_path|
puts "cr: #{cr.inspect}"
puts "att: #{att.inspect}, att."
puts "do_path: #{do_path.inspect}"
puts "#{att.ink_rect.x},#{att.ink_rect.y},#{att.ink_rect.width},#{att.ink_rect.height},#{att.value},#{att.data}"
puts "index_to_pos: #{layout.index_to_pos(att.start_index)}"
puts "index_to_pos.x: #{layout.index_to_pos(att.start_index).x}"
puts "index_to_pos.y: #{layout.index_to_pos(att.start_index).y}"
x = layout.index_to_pos(att.start_index).x / Pango::SCALE
y = layout.index_to_pos(att.start_index).y / Pango::SCALE
cxt.rounded_rectangle(x,y,ico_w,ico_h,0) # use the outer context?
cxt.set_source_color('blue')
cxt.fill
[cr.class, att.class, do_path]
end
ink_gap = Pango::Rectangle.new(0, 0, ico_w * Pango::SCALE, 0)
log_gap = Pango::Rectangle.new(0, 0, ico_w * Pango::SCALE, 0)
attrs = Pango::AttrList.new
att = Pango::AttrShape.new(ink_gap, log_gap)
att.start_index = text[0, text.index("!")].bytesize
att.end_index = att.start_index + "!".bytesize
attrs.insert(att)
att = Pango::AttrShape.new(ink_gap, log_gap)
att.start_index = text[0, text.index("g")].bytesize
att.end_index = att.start_index + "g".bytesize
attrs.insert(att)
att = Pango::AttrShape.new(ink_gap, log_gap)
att.start_index = text[0, text.index("is")].bytesize
att.end_index = att.start_index + "is".bytesize
attrs.insert(att)
layout.attributes = attrs
puts "Spacing: #{layout.spacing}"
cxt.show_pango_layout(layout)
cxt.target.write_to_png('pangofun_output.png')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment