objectFit static method
void
objectFit(})
Resizes and positions object
inside a container defined by canvasW
and
canvasH
. If objW
and objH
are provided, they should be the original
size of the asset. The fit
parameter works similar to BoxFit in Flutter.
If reposition
is true, the object will be centered in the container
after resizing.
Implementation
static void objectFit(
GDisplayObject object, {
BoxFit fit = BoxFit.cover,
double? objW,
double? objH,
required double canvasW,
required double canvasH,
bool reposition = false,
}) {
if (objW == null || objH == null) {
/// calculate real objects bounds.
if (object is GBitmap) {
objW ??= object.texture!.width;
objH ??= object.texture!.height;
} else {
final bounds = object.bounds!;
objW ??= bounds.width;
objH ??= bounds.height;
}
}
var r1 = objW! / objH!;
var r2 = canvasW / canvasH;
// Determine resize behavior based on fit parameter
if (fit == BoxFit.scaleDown) {
fit = objW > canvasW || objH > canvasH ? BoxFit.contain : BoxFit.none;
}
if (fit == BoxFit.cover) {
if (r2 > r1) {
object.width = canvasW;
object.scaleY = object.scaleX;
} else {
object.height = canvasH;
object.scaleX = object.scaleY;
}
} else if (fit == BoxFit.contain) {
if (r1 > r2) {
object.width = canvasW;
object.scaleY = object.scaleX;
} else {
object.height = canvasH;
object.scaleX = object.scaleY;
}
} else if (fit == BoxFit.fill) {
object.width = canvasW;
object.height = canvasH;
} else if (fit == BoxFit.none) {
object.width = objW;
object.height = objH;
} else if (fit == BoxFit.fitHeight) {
object.height = canvasH;
object.scaleX = object.scaleY;
} else if (fit == BoxFit.fitWidth) {
object.width = canvasW;
object.scaleY = object.scaleX;
}
// Reposition object if requested
if (reposition) {
if (object.pivotX == 0) {
object.x = (canvasW - object.width) / 2;
object.y = (canvasH - object.height) / 2;
} else {
object.x = canvasW / 2;
object.y = canvasH / 2;
}
}
}