Method: HexaPDF::Content::Canvas#opacity
- Defined in:
- lib/hexapdf/content/canvas.rb
#opacity(fill_alpha: nil, stroke_alpha: nil) ⇒ Object
:call-seq:
canvas.opacity => current_values
canvas.opacity(fill_alpha:) => canvas
canvas.opacity(stroke_alpha:) => canvas
canvas.opacity(fill_alpha:, stroke_alpha:) => canvas
canvas.opacity(fill_alpha:, stroke_alpha:) { block } => canvas
The fill and stroke alpha values determine how opaque drawn elements will be. Note that the fill alpha value applies not just to fill values but to all non-stroking operations (e.g. images, …).
Returns the current fill alpha (see GraphicsState#fill_alpha) and stroke alpha (see GraphicsState#stroke_alpha) values using a hash with the keys :fill_alpha and :stroke_alpha when no argument is given. Otherwise sets the fill and stroke alpha values and returns self. The setter version can also be called in the #opacity= form.
If the values are set and a block is provided, the changed alpha values are only active during the block by saving and restoring the graphics state.
Examples:
#>pdf
canvas.opacity(fill_alpha: 0.5)
canvas.opacity # => {fill_alpha: 0.5, stroke_alpha: 1.0}
canvas.opacity(fill_alpha: 0.4, stroke_alpha: 0.9)
canvas.opacity # => {fill_alpha: 0.4, stroke_alpha: 0.9}
canvas.opacity(stroke_alpha: 0.7) do
canvas.opacity # => {fill_alpha: 0.4, stroke_alpha: 0.7}
end
canvas.opacity # => {fill_alpha: 0.4, stroke_alpha: 0.9}
# visual example
canvas.opacity(fill_alpha: 1, stroke_alpha: 1)
canvas.fill_color("hp-gray-light"). # background rectangle on right side
rectangle(100, 0, 100, 200).fill
canvas.opacity(fill_alpha: 0.5, stroke_alpha: 0.8). # foreground rectangle, with a thick
line_width(20). # stroke that also overlays the
fill_color("hp-blue").stroke_color("hp-blue"). # inside of the rectangle, creating
rectangle(20, 20, 160, 160).fill_stroke # multiple shadings due to opacity
See: PDF2.0 s11.6.4.4
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 |
# File 'lib/hexapdf/content/canvas.rb', line 1009 def opacity(fill_alpha: nil, stroke_alpha: nil) if !fill_alpha.nil? || !stroke_alpha.nil? raise_unless_at_page_description_level_or_in_text save_graphics_state if block_given? if (!fill_alpha.nil? && graphics_state.fill_alpha != fill_alpha) || (!stroke_alpha.nil? && graphics_state.stroke_alpha != stroke_alpha) dict = {Type: :ExtGState} dict[:CA] = stroke_alpha unless stroke_alpha.nil? dict[:ca] = fill_alpha unless fill_alpha.nil? dict[:AIS] = false if graphics_state.alpha_source invoke1(:gs, resources.add_ext_gstate(dict)) end if block_given? yield restore_graphics_state end self elsif block_given? raise ArgumentError, "Block only allowed with an argument" else {fill_alpha: graphics_state.fill_alpha, stroke_alpha: graphics_state.stroke_alpha} end end |