Skip to content

Centres

  • by

Change the co-ordinates of an overlay FROM its centre relative to canvas centre TO its top left corner relative to canvas top left corner (0,0)
W= canvas width
H= canvas height
w= overlay width
h = overlay height
cx = overlay centre x relative to canvas centre x
( left of canvas centre cx is negative, right of canvas centre cx is positive )
cy = overlay centre y relative to canvas centre y
( above canvas centre cy is negative, below canvas centre cy is positive )

Position of top left corner of overlay relative to top left corner of canvas is;
x=((W-w)/2)+cx
y=((H-h)/2)+cy

This is probably useful if you want to place images. If you calculate from their centres it doesn’t matter how big the images are.

use Image::Imlib2;
my ($x,$y,$x1,$y1,$w,$h,$canw,$canh);
$canw=400;
$canh=400;
my $image0=Image::Imlib2->new($canw,$canh);
$image0->has_alpha(255);
$x=-100;
$y=-100;
$w=100;###<<<<
$h=100;###<<<<
$x1=(($canw-$w)/2)+$x;
$y1=(($canh-$h)/2)+$y;
$image0->set_color(0,0,255,100);#blue
$image0->fill_rectangle($x1,$y1,$w,$h);

$x=-100;
$y=-100;
$w=200;###<<<<
$h=200;###<<<<
$x1=(($canw-$w)/2)+$x;
$y1=(($canh-$h)/2)+$y;
$image0->set_color(255,0,0,100);#red
$image0->fill_rectangle($x1,$y1,$w,$h);

$image0->save('rectangle3.png');