Skip to content

Instantly share code, notes, and snippets.

@Pikachu920
Created October 15, 2017 05:45
Show Gist options
  • Save Pikachu920/6c8726251929543627867e2dc48854a1 to your computer and use it in GitHub Desktop.
Save Pikachu920/6c8726251929543627867e2dc48854a1 to your computer and use it in GitHub Desktop.
function drawCenteredString(image: object, input: text, font: object):
#Get BufferedImage
set {_image-file} to new {File}({_image})
if {_image-file}.exists():
set {_image} to {ImageIO}.read({_image-file})
set {_image-width} to {_image}.getWidth()
set {_image-height} to {_image}.getHeight()
set {_graphics} to {_image}.getGraphics()
# Get the FontMetrics
set {_metrics} to {_graphics}.getFontMetrics({_font})
# Determine the X coordinate for the text
set {_args::*} to 0, 0, {_image-width} and {_image-height}
set {_rectangle} to new {Rectangle}({_args::*})
set {_x} to {_rectangle}.x!
set {_width} to {_rectangle}.width!
set {_stringWidth} to {_metrics}.stringWidth({_input})
set {_x} to {_x} + (({_width} - {_stringWidth}) / 2)
# Determine the Y coordinate for the text (note we add the ascent, as in java 2d 0 is top of the screen)
set {_y} to {_rectangle}.y!
set {_height} to {_rectangle}.height!
set {_stringHeight} to {_metrics}.getHeight()
set {_ascent} to {_metrics}.getAscent()
set {_y} to {_y} + (({_height} - {_stringHeight}) / 2) + {_ascent}
# Set the font
{_graphics}.setFont({_font});
# Draw the String
{_graphics}.drawString({_input}, {_x} and {_y});
set {_args::*} to {_image}, "png" and {_image-file}
{ImageIO}.write({_args::*});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment