How to center an image on a canvas

How to center an image on a canvas for example when my canvas is 800x800pixels and my image is 450x800 because it always aligns the left side

g.drawpicture mypic,(g.width-mypic.width)/2,(g.height-mypic.height/2)

Dave S, thanks for your help, it was really what I needed !


it always draw the image at 0,0 (top, left), unless your image have the same size of your canvas or one of the two values are identical as in your example: 800 x 800 / 450 x 800 OR 800 x 800 / 800 x 450.

Thanks for everyone’s help, I appreciate!

An old thread, but Thanks Dave, glad I found this.

One thing I noticed was as is, the code only centres the image across the width, not the height.

After fiddling around I added another set of parentheses:

g.drawpicture mypic, ((g.width-mypic.width)/2,(g.height-mypic.height)/2)

Now centres the image both ways :slight_smile:


I would have expected the fix to be to simply move one of the brackets

g.drawpicture mypic, (g.width-mypic.width)/2 , (g.height-mypic.height/2) becomes g.drawpicture mypic, (g.width-mypic.width)/2 , (g.height-mypic.height)/2

the height of the canvas minus the height of the picture… giving the amount of ‘white space’
Then divide that by two to make the white space even top and bottom

Adding the extra brackets wasn’t the fix, but putting the closing bracket before the /2 did it.

Right you are Jeff - it works as well (and simpler).

I didn’t try that one thinking that “surrounding” brackets were required.
I was think along the lines of a math equation where the last “/ 2” would divide all the previous calculations by 2.