Added support for using an image in a button

This commit is contained in:
2020-06-09 10:49:31 -05:00
parent 5b2a015421
commit 39964e5bd4

View File

@@ -1,14 +1,31 @@
module CyberarmEngine module CyberarmEngine
class Element class Element
class Button < Label class Button < Label
def initialize(text, options = {}, block = nil) def initialize(text_or_image, options = {}, block = nil)
super(text, options, block) if text_or_image.is_a?(Gosu::Image)
@image = text_or_image
@scale_x, @scale_y = 1, 1
end
super(text_or_image, options, block)
@style.background_canvas.background = default(:background) @style.background_canvas.background = default(:background)
end end
def render def render
draw_text if @image
draw_image
else
draw_text
end
end
def draw_image
@image.draw(
@style.border_thickness_left + @style.padding_left + @x,
@style.border_thickness_top + @style.padding_top + @y,
@z + 2,
@scale_x, @scale_y, @text.color)
end end
def draw_text def draw_text
@@ -62,6 +79,54 @@ module CyberarmEngine
return :handled return :handled
end end
def recalculate
if @image
@width, @height = 0, 0
_width = dimensional_size(@style.image_width, :width)
_height= dimensional_size(@style.image_height,:height)
if _width && _height
@scale_x = _width.to_f / @image.width
@scale_y = _height.to_f / @image.height
elsif _width
@scale_x = _width.to_f / @image.width
@scale_y = @scale_x
elsif _height
@scale_y = _height.to_f / @image.height
@scale_x = @scale_y
else
@scale_x, @scale_y = 1, 1
end
@width = _width ? _width : @image.width.round * @scale_x
@height= _height ? _height : @image.height.round * @scale_y
update_background
else
super
end
end
def value
@image ? @image : super
end
def value=(value)
if value.is_a?(Gosu::Image)
@image = value
else
super
end
old_width, old_height = width, height
recalculate
root.gui_state.request_recalculate if old_width != width || old_height != height
publish(:changed, self.value)
end
end end
end end
end end